package 子类; class Grandparent{ public Grandparent() { System.out.println("GrandParent Created."); } public Grandparent(String string) { System.out.println("GrandParent Created.String:" + string); } } class Parent extends Grandparent { public Parent() { //super("Hello.Grandparent."); System.out.println("Parent Created"); // super("Hello.Grandparent."); } } class Child extends Parent { public Child() { System.out.println("Child Created"); } } class TestInherit { public static void main(String[] args) { Child c = new Child(); } }
构造一个对象,先调用其构造方法,来初始化其成员函数和成员变量。
子类拥有父的成员变量和成员方法,如果不调用,则从父类继承而来的成员变量和成员方法得不到正确的初始化。
不能反过来调用也是这个原因,因为父类根本不知道子类有神魔变量而且这样一来子类也得不到初始化的父类变量,导致程序运行出错!
package 子类; class Parent { int x; public Parent() { System.out.println("Parent Created1"); } public void show(){ System.out.println("Parent Created2"); } } class Child extends Parent { int y; public Child() { System.out.println("Child Created1"); } public void show(){ super.show(); System.out.println("Parent Created3"); } } public class text { public static void main(String args[]) { Child c = new Child(); c.show(); } }
在继承结构里面,为了保护封闭原则,通常子类以继承之后,子类可以直接调用父类非私有方法,也就是除了private修饰的方法。
从多太的角度来看,子类是可以继承父类的方法,如果一个子类继承了父类的方法,那么不用super关键字就是调用本类的方法,如果想调用父类的话就要加super。
package 子类; class Parent{ public int myValue=100; public void printValue() { System.out.println("Parent.printValue(),myValue="+myValue); } } class Child extends Parent{ public int myValue=200; public void printValue() { System.out.println("Child.printValue(),myValue="+myValue); } } public class ParentChildTest { public static void main(String[] args) { Parent parent=new Parent(); parent.printValue(); Child child=new Child(); child.printValue(); parent=child; parent.printValue(); parent.myValue++; parent.printValue(); ((Child)parent).myValue++; parent.printValue(); } }
当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。