目录
一、类的继承
在subroutine.java中:
class Parent{
Parent(){
System.out.println("调用父类的Parent()构造方法");
}
}
class SubParent extends Parent{
SubParent(){
System.out.println("调用子类的subParent()构造方法");
}
}
public class subroutine extends SubParent {
subroutine(){
System.out.println("调用子类的subroutine()构造方法");
}
public static void main(String[] args) {
subroutine obj = new subroutine();
}
}
运行结果为:
在实例化子类对象时,父类无参构造方法将被自动调用,但又参构造方法不能被自动调用。只能依赖于super关键字显式调用父类的构造方法。创建一个子类对象,将包含一个父类子对象。当实例化子类对象时,父类对象也相应被实例化。
(以下具体代码)
class text{
text(){
System.out.println("call the constructor of text()");
}
public void doSomething() {
System.out.println("doSomething");
}
protected text dolt() {
return new text();
}
}
public class text2 extends text{
text2(){
super();
System.out.println("call the constructor of text2()");
}
public void doSomething() {
System.out.println("doSomething in class text2");
}
public void doNew() {
System.out.println("doNew here");
}
protected text2 dolt() {
return new text2();
}
public static void main(String[] args) {
text2 obj = new text2();
obj.doSomething(); //执行text2类中的方法
obj.doNew();
obj.dolt(); //执行text2类中的方法
}
}
结果为:
call the constructor of text() | 创建父类对象 |
call the constructor of text2() | 创建子类对象 |
doSomething in class text2 | 调用text2中的重写方法 |
doNew here | 调用text2中新添加的方法 |
call the constructor of text() | 调用text2中的dolt()方法,创建对象,先创建一个父类对象 |
call the constructor of text2() | 再创建一个子类对象 |
1. super关键字:
可以在子类的构造方法中调用super()语句调用父类的构造方法;也可以在子类中使用super关键字调用父类的成员方法(仅public、protected)。
2. 重写(覆盖)父类的成员方法:
将父类成员方法的名称保留,
1)重写成员方法的实现内容 | |
2)更改成员方法的存储权限: | 只能从小范围改到大范围 |
3)修改成员方法的返回类型: | 遵循:重写的返回值类型必须是父类该方法的返回值类型的子类 |
重写方法的调用: |
||
1)用实例化对象是调用不到父类的 | 在内存中仍为子类对象 | |
2)只能用super关键字 | 1)且只能在类方法中调用 2)在main(类外部)是调用不到的 |
|
(最初overrride的设计意图之一) |
class Father{