继承
实例
-
主程序
import oop.day14.Person; import oop.day14.Student; public class Application { public static void main(String[] args) { Student student = new Student(); student.say(); System.out.println(student.money); Person xd= new Person(); xd.setUsdt(999); xd.getUsdt(); System.out.println(xd.getUsdt()); } }
-
父类
//父类 java中,所有的类,都默认直接或间接继承Object类 Ctrl + H
public class Person {
//public 继承为该属性,权限大小由上至下
//protected
//defauilt 默认的修饰符
//private该类型无法继承
public int money = 10_0000_0000;
private int usdt = 10_0000;
public int getUsdt() {
return usdt;
}
public void setUsdt(int usdt) {
this.usdt = usdt;
}
public void say(){
System.out.println("xy是巴西龟");
}
}
-
子类
//Person的子类 //子类继承了父类,就会有父类的所有方法 public class Student extends Person{ }
super的用法
实例
-
子类
public class Student01 extends Person01{ private String name = "xx"; public void test(String name){ System.out.println(name);//通过对象传递值 System.out.println(this.name);//本类中的值 System.out.println(super.name);//通过super继承父类的值 } }
父类
public class Person01 {
public String name = "xd是巴西龟";
}
主程序对象
public class Application {
public static void main(String[] args) {
Student01 student01 = new Student01();
student01.test("巴西龟是小戴");
super注意点
- super调用父类的构造方法,必须在构造方法的第一个
- super必须只能出现在子类的方法或者构造方法中
- super和this不能同时调用构造方法
和this对比:
-
代表的对象不同
this: 本身调用者这个对象
super:代表父类对象的应用
-
前提
this:没继承也可以使用
super:只能在继承条件才可以使用
-
构造方法
this():本类的构造
super():父类的构造