对于继承,我们都知道当子类继承父类的时候,子类会继承父类所有(public)的属性和方法。
这里我们用一个Parent类和Child类来进行示例,其中Child继承Parent。
Parent类:
public class Parent
{
public Parent() {
System.out.println("父类的构造函数。。。");
}
}
Child类:
public class Child extends Parent
{
public Child() {
System.out.println("子类的构造函数。。。");
}
}
主函数:
public static void main(String[] args)
{
Child a = new Child();
System.out.println("exit");
}
运行结果:
分析:
在上述代码中,我在父类Parent的构造方法中添加了一条输出语句:
System.out.println("父类的构造函数。。。");
在子类Child的构造方法中添加了一条输出语句:
System.out.println("子类的构造函数。。。");
在主函数中,创建了一个Child类的对象,然后在构造结束后面添加了输出语句:
System.out.println("exit");
在创建的时候会调用该对象的构造方法。
根据程序的输出可以看得出:当构造子类对象的时候会先调用父类的构造方法,执行完之后再调用子类的构造方法。整个构造过程调用了连个构造方法。
Parent类:
public class Parent
{
public Parent() {
System.out.println("父类的构造函数。。。");
}
public void show()
{
System.out.println("父类的输出...");
}
}
Child类:
public class Child extends Parent
{
public Child() {
System.out.println("子类的构造函数。。。");
}
public void show()
{
System.out.println("子类的输出...");
}
}
主函数:
public class HelloWorld
{
public static void main(String[] args)
{
Child a = new Child();
a.show();
System.out.println("exit");
}
}
运行结果:
分析:
在父类Parent中,添加了一个方法,用于输出一个语句:
public void show()
{
System.out.println("父类的输出...");
}
在子类Child中,同样添加了一个同名的方法,用于输出一个语句:
public void show()
{
System.out.println("子类的输出...");
}
在主函数中创建对象后调用方法show(),根据输出结果可以看出,子类的show()方法掩盖了父类的show()方法,所以在主函数中调用执行的是子类的show()方法,并没有调用父类的show()方法。
修改子类Child的show()方法,为其添加一个参数,修改后代码如下:
public class Child extends Parent
{
public Child() {
System.out.println("子类的构造函数。。。");
}
public void show(int pos)
{
System.out.println("子类的输出:" + pos);
}
}
主函数添加对子类Child中show()的调用:
public static void main(String[] args)
{
Child a = new Child();
a.show();
a.show(2015);
System.out.println("exit");
}
运行结果:
分析:
结合修改前的代码可以看出:子类只会屏蔽父类中和其形式相同(方法明和参数列表都相同)的方法。
修改子类Child中的show()方法,使用super关键字。修改后代码如下:
public class Child extends Parent
{
public Child() {
System.out.println("子类的构造函数。。。");
}
public void show()
{
super.show();
System.out.println("子类的输出...");
}
}
将主函数修改回原来形式:
public static void main(String[] args)
{
Child a = new Child();
a.show();
System.out.println("exit");
}
运行结果: