public class Child extends Parent{ public Child() { System.out.println("child"); } public static void main(String[] args) { Child child = new Child(); } }
class Parent{ public Parent() { System.out.println("parent"); } }
public class Child extends Parent{ public Child() { super(1); System.out.println("child"); } public static void main(String[] args) { Child child = new Child(); } }
class Parent{ // public Parent() { // System.out.println("parent"); // } public Parent(int i) { System.out.println("parent"); } }
public class PolyTest { public static void main(String[] args) { //Parent parent = new Parent(); //parent.sing(); //Child child = new Child(); //child.sing();
Parent p = new Child(); p.sing(); } }
class Parent { /* public void sing() { System.out.println("parent is singing"); } */ }
class Child extends Parent { public void sing() { System.out.println("child is singing"); } }
Parent p = new Child();当使用多态方式调用方法时,首先检查父类中是否有sing()方法,如果没有则编译错误;如果有,再去调用子类的sing()方法。
public class PolyTest3 { public static void main(String[] args) { //Fruit f = new Pear(); //f.run(); //Pear p = (Pear)f; //p.run(); //是不可以的,父类中没有grow(),强制类型转换后可以 //Fruit f = new Pear(); //f.grow();
Fruit f = new Pear();
Pear p = (Pear)f; p.grow(); } }
class Fruit { public void run() { System.out.println("fruit is running"); } }
class Pear extends Fruit { public void run() { System.out.println("pear is running"); }
public void grow() { System.out.println("pear is growing"); } }
public class PolyTest4 { public static void main(String[] args) { A a = null;
if(args[0].equals("1")) { a = new B(); } else if(args[0].equals("2")) { a = new C(); } else if(args[0].equals("3")) { a = new D(); }
a.method(); } }
class A { public void method() { System.out.println("A"); } }
class B extends A { public void method() { System.out.println("B"); } }
class C extends A { public void method() { System.out.println("C"); } }
class D extends A { public void method() { System.out.println("D"); } }
晚绑定,编译的时候不知道,等到执行的时候才能确定下来具体的子类。
Connecting a function call to a function body is called binding.(将函数体和函数调用关联起来,就叫绑定)
早绑定(Early binding)
1 2
When binding is performed before the program is run (by the compiler and linker), it' s called early binding 在程序运行之前(也就是编译和链接时),执行的绑定是早绑定。
晚绑定(late binding)
1
late binding, which means the binding occurs at runtime, based on the type of the object. When a language implements late binding, there must be some mechanism to determine the type of the object at runtime and call the appropriate member function.
public class EncapTest{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; } }