继承
- 继承的本质是
子类通过继承父类的方式获得父类的protected变量和方法使用权(is a),所有类都继承Object类,Object类是所有类的父类
- extends
子类是父类的扩展,java中只有单继承,没有多继承,
- 继承是类和类之间的一种关系
- 继承关系的两个类,一个为父类(基类),一个为派生类(子类)
定义Extending类
public class Extending {
// 父类的属性
public int money;
private int house;
// 父类的方法
public void gold(){
this.money = 1000;
System.out.println(money);
}
public int getHouse(){
return house;
}
public void setHouse(int house){
this.house = house;
}
}
定义一个Father类继承Extending类
public class Father extends Extending {
String car;
public void drive(){
car = "在开车";
System.out.println(car);
}
}
定义一个Son类继承Father类
public class Son extends Father{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
启动类Application
public class Application {
public static void main(String[] args) {
Son son = new Son();
son.setAge(10);
System.out.println("小明今年:"+son.getAge()+"岁");
son.drive();
System.out.print("这个车价值:");
son.gold();
}
}
输出结果为:
小明今年:10岁
开着爸爸的车
这个车价值:1000
This--super关键字的区别
父类SuperText02
public class SuperText02 {
protected String name = "张三";
}
子类SuperText01
public class SuperText1 extends SuperText02 {
protected String name = "李四";
public void eat(String name){
System.out.println("这是此方法形参的name:"+name);
System.out.println("这是子类属性name:"+this.name);
System.out.println("这是父类的属性name:"+super.name);
}
}
测试类Application
public class Application {
public static void main(String[] args) {
SuperText1 superText1 = new SuperText1();
superText1.eat("王五");
}
}
结果为:
这是此方法形参的name:王五
这是子类属性name:李四
这是父类的属性name:张三
- super
super关键字可以直接引用父类的属性,但是使用this关键字引用的是当前子类自身的属性,方法也是同理
super调用父类方法必须在方法体最开始声明
super必须出现在子类的方法过构造方法中
super和this不能同时调用构造方法
- this与super的区别
1.代表的对象不同
this:当前类对象的调用
super:代表父类对象的引用
2.前提不同
this:没有继承也可以使用
super:继承的情况下在子类中使用
3.调用的构造方法不同
this:调用的时本类的构造方法
super:调用的时父类的构造方法