运行结果:
总结:
1.有继承类的情况下,在进行方法调用或函数构造时系统会先构造基类在构造父类最后在构造子类
2.通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。
问题:为什么子类的构造方法在运行之前,必须调用父类的构造方法?能不能反过来?为什么不能反过来?
1.构造函数主要用来在创建对象时初始化对象,即为对象成员变量赋初值
2.构造一个对象,先调用其构造方法,来初始化其成员函数和成员变量。
3.子类拥有父类的成员变量和成员方法,如果不调用,则从父类继承而来的成员变量和成员方法得不到正确的初始化。
4.父类不能调用子类,因为父类不知道子类有什么变量,而且子类得不到初始化的父类变量。
二、探索
public class ExplorationJDKSource { /** * @param args */ public static void main(String[] args) { System.out.println(new A()); } } class A{}
结果:
三、
package first; public class Fruit { public String toString() { return "Fruit toString."; } public static void main(String args[]) { Fruit f=new Fruit(); System.out.println("f="+f); System.out.println("f="+f.toString()); } }
运行结果:
原因:在“+”号运算时,当任何一个对象与String对象连接时,会隐式调用其toString()方法,默认情况下,此方法返回“类名@+hashCode"为返回有意义的信息,子类可以重写toString()方法。
四、多态
instanceof运算符判断一个对象是否可以转换为指定的类型
注意:Object是Java类库中的顶层类,即所有类的父类;所以子类对象可以直接赋值给父类变量;即子类对象可以被当成父类对象来使用
五、方法覆盖:自行编写代码测试“在子类中,若要调用父类中被覆盖的方法,可以使用super关键字
package second; /** * 父类B * @author ASUS * */ class B{ B(){ System.out.println("I am B."); } } /** * 子类A * @author ASUS * */ class A extends B{ A(){ super(); //调用父类的构造方法 } public static void main(String[] args){ new B(); //实例化类B的对象 } }
注意:(1)覆盖方法允许访问范围不能小于原方法
(2)声明为final的方法不允许覆盖
(3)不能覆盖静态static方法
六、多态性
(1)子类对象可以被当成父类或基类对象使用;如:Parent p=new Child();
即:更一般的对象可容纳更具体化的对象。(类Object的对象可以被 所有类赋值)
package first; public class TestInstanceof { public static void main(String[] args) { //声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类 //但hello变量的实际类型是String Object hello = "Hello"; //String是Object类的子类,所以返回true。 System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object)); //返回true。 System.out.println("字符串是否是String类的实例:" + (hello instanceof String)); //返回false。 System.out.println("字符串是否是Math类的实例:" + (hello instanceof Math)); //String实现了Comparable接口,所以返回true。 System.out.println("字符串是否是Comparable接口的实例:" + (hello instanceof Comparable)); String a = "Hello"; //String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过 //System.out.println("字符串是否是Math类的实例:" + (a instanceof Math)); } }
(2)父类对象赋值给子类变量必须进行强制类型转换。
七、代码验证
package second; class Parent { public int value=100; public void Introduce() { System.out.println("I'm father"); } } class Son extends Parent { public int value=101; public void Introduce() { System.out.println("I'm son"); } } class Daughter extends Parent { public int value=102; public void Introduce() { System.out.println("I'm daughter"); } } public class TestPolymorphism { public static void main(String args[]) { Parent p=new Parent(); p.Introduce(); System.out.println(p.value); p=new Son(); p.Introduce(); System.out.println(p.value); p=new Daughter(); p.Introduce(); System.out.println(p.value); } }
结果:
自parent=child 语句后,parent 其实就是child;