父类
public class Father {
static String d="father++";
public Father() {
System.out.println("father");
}
public void test() {
System.out.println("father test");
}
public void play() {
System.out.println("父类独有");
}
}
子类
public class Child extends Father {
static String d="child++";
public Child() {
System.out.println("child");
}
public void test() {
System.out.println("child test");
}
public void special() {
System.out.println("子类特殊的方法");
}
}
测试函数
public class FatherAndChild {
public static void main(String[] args) {
Father father = new Child();
father.test();
father.play();
System.out.println(father.d);
father = new Child();
System.out.println(father.d);
father.test();
System.out.println("++++++++++++++++++++++++++++++++++");
father = new Father();
father.test();
System.out.println("++++++++++++++++++++++++++++++++++");
Child child = new Child();
child.test();
System.out.println(child.d);
System.out.println("++++++++++++++++++++++++++++++++++");
Father newfather = new Father();
}
}
运行结果
father
child
child test
父类独有
father++
father
child
father++
child test
++++++++++++++++++++++++++++++++++
father
father test
++++++++++++++++++++++++++++++++++
father
child
child test
child++
++++++++++++++++++++++++++++++++++
father
多态:是子类对父类相同基因(相同方法)下的不同表达方式,如同生物多样性。
分析:
第一种 Father father = new Father(); 很简单,调用的方法,变量,构造函数都是自己的。
第二种 Father father = new Child();
变量 | 构造方法 | 独有方法 | 相同普通方法 | |
未重写 | 父类变量 | 初始化调用 只有父类构造方法(还初始化子类构造,不过默认没有输出) | 父类独有方法 | 父类普通方法 |
重写后 | 父类变量 | 先输出父类构造,后输出子类构造 | 可以调用父类独有,无法调用子类独有方法 | 子类普通方法 |
new 类()是实例化,所以后面new的什么,就按它普通new 初始化构造方法
比如:Father father = new Father(); 只初始化父类构造
Child child = new Child(); 初始化 父类构造 、子类构造
Father father = new Child(); 初始化 父类构造 、子类构造
含义:Father father = new Child(); 这种可以这样理解,看实例化new Child()知道它存在什么资源,看前面Father father 引用类型 知道它可以使用什么资源。
这里 new Child()说明它拥有了父类和子类的全部内容,Father father 引用类型 说明 只能用父类的那一部分。
对于这种 Father father = new Child();
总计:1.只能调用父类的变量,即使子类定义相同变量。
2.初始化看new的是什么实例,根据它初始化构造方法。
3.调用看能力,无法调用子类独有的方法。
4.可以调用父类的普通方法,如果子类重写,调用的将是子类的方法。
结论4就是多态实现的重要依据。