06继承
本质是对一批类的抽象,类与类之间的一种关系。使用extends
子类继承了父类,就会拥有父类的全部方法!JAVA中只有单继承,只有一个父类。私有方法无法继承
例1:
//在java中,所有的类,都默认直接或者间接继承Object
public class Person {
private int money =1000_000;
public void say(){
System.out.println("说了一句话");
}
public int getMoney(){
return money;
}
}
//学生也是人
public class Student extends Person {
//ctr+H
}
public class Application {
public static void main(String[] args) {
Student s1=new Student();
s1.say();
System.out.println(s1.getMoney());
}
}
运行结果:
说了一句话
1000000
例2:this 和super
super注意点:1.super调用父类的构造方法,必须在构造方法的第一个。
2.super必须只能出现在子类的方法或者构造方法中!
3.super和this不能同时调用构造方法。
VS this
代表的对象不同:
this :本身调用者这个对象
super:代表父类对象的应用
前提:this 没有继承也可以使用
super只能在继承条件才可以使用
构造方法
this();本类的构造,
super():父类的构造。
public class Person {
protected String name="狂神";
public void print(){
System.out.println("person");
}
public class Student extends Person {
//ctr+H
private String name = "秦将";
public void print(){
System.out.println("student");
}
public void test1(){
print();
this.print();
super.print();
}
public void test(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
}
}
public class Application {
public static void main(String[] args) {
Student s1=new Student();
s1.test("qinjiang");
s1.test1();
}
}
运行结果:
qinjiang
秦将
狂神
student
student
person

浙公网安备 33010602011771号