重写超类如何知道方法而不创建对象。在这段代码中,我创建了一个子类的对象,并存储在超类的引用中。
public class A{
public void show(){
System.out.println("A");
}
}
public class sub extends A{
public void display(){
System.out.println("Displaay");
}
public static void main(String []arg){
sub s = new sub();
s.display();
A a= new sub();
a.show();
}
}
a a = new sub(); >当我调用a.show()时。它显示了一个方法。为什么,因为我正在创建一个子类的对象。如果子类dones有show方法。它应该给出一个错误但是我们继承了A类,它默认应该是超级的。
在A a = new sub();
答案 0 :(得分:0)
当您扩展课程时,您会自动了解父课程中的所有方法。
但要小心,扩展和覆盖不是一回事。
public class Father{
public void display(){
//print father
}
public void hello(){
//print father
}
}
}
public class Son extends Father{
@Override
//the annotation isn't an obligation it's just more 'clean'
public void display(){
//print son
}
}
Son.hello是一个扩展函数。
Son.display是一个覆盖函数调用。