我们发现,子类可以继承父类里面的方法,那么,子类可以继承父类的父类的方法吗?
通过一个小示例来观察一下,
class GrandFather{
int num=10;
int num2=20;
}
class Father extends GrandFather{
int num3=30;
int num4=40;
public void method(){
System.out.println(num);
System.out.println(num2);
}
}
class Son extends Father{
public void show(){
System.out.println(num);
System.out.println(num2);
}
}
public class jicheng_biduan {
public static void main(String[] args) {
Son son = new Son();
son.method();
System.out.println("--------------------");
son.show();
}
}
运行结果为:
由此我们可以发现,子类可以继承任何一个父类的public方法和变量,因为Java中没有多继承,但Java中有多层继承,所以子类可以 继承父类的父类的父类。
我们知道当一个变量在代码中遵循就近原则,通过下面一段代码体现。。
class Father {
int num1=30;
int num2=40;
}
class Son extends Father{
int num1 = 60;
public void show(){
int num1=90;
System.out.println(num1);
}
}
public class jicheng_biduan {
public static void main(String[] args) {
Son son = new Son();
son.show();
}
}
输出结果为:
在father类中定义了num1,son类中也定义了num1,在son类中的show方法也定义了num1,但由输出结果可知最后show方法调用的是show方法里面的num1,所以我们说的调用遵循"就近原则"。
但是当我们想调用show方法外面的num1时,我们该怎么办呢?
这时我们想到了关键词this我们说过,this代表的是当前类,但在继承中我想访问父类之中的同名变量,怎么办呢?有相应的关键字供我们使用吗!答案是有的,关键字时"super"。"super"关键字可以让我们匹配到父类之中的同名变量。举一个简单的小例子。
class Father {
int num1=30;
}
class Son extends Father{
int num1 = 60;
public void show(){
int num1=90;
System.out.println(num1);
System.out.println(this.num1);
System.out.println(super.num1);
}
}
public class jicheng_biduan {
public static void main(String[] args) {
Son son = new Son();
son.show();
}
}
运行结果为:
由运行结果可得,已成功调用方法外类中的变量,和父类中的同名变量,
System.out.println(this.num1);
System.out.println(super.num1);
这两句话可以发现,我们已经成功用this关键字和super关键字调用成功。
其实,this关键字,super关键字不仅可以调用成员变量,this,super关键字用法:
1.调用成员变量,
this.(变量名)
super.(变量名)
2.调用构造方法,
this(参数) 调用本类构造方法
super(参数) 调用父类构造方法
3.调用成员方法
this.成员方法 调用本类
super.成员方法 调用父类