class People {
People() {
System.out.println("我是人");
}
}
class Student extends People {
Student(int a, String name) {
this(a);
System.out.println(a);
System.out.println(name);
}
Student(int b) {
super();
System.out.println(++b);
}
}
class Student2 extends People {
}
class Demo1 {
public static void main(String[] args) {
Student s = new Student(4, "李帅");
}
}
这段代码不知道能不能看懂?首先先介绍一下super,我们之前调用子类方法,可以很爽的使用父类中的属性和方法,它为什么可以调用父类的东西?那是因为有super这个东西,在你创建子类对象时,有一个隐式的构造方法,在这个隐式的构造方法中第一行又有一个super();调用了父类的构造方法,构造方法具有创建对象的功能,所以在创建子类对象时,父类就也跟着创建了。
上面的代码有一个this();的传递,this();是调用其它构造方法的。
class Pone {
void call() {
System.out.println("我只能打电话");
}
}
class Newpone {
void call() {
System.out.println("我不仅能打电话还能聊天");
System.out.println(this);
}
}
class Demo1 {
public static void main(String[] args) {
Newpone n = new Newpone();
n.call();
}
}
上面的代码完成了对父类方法的重写,首先你能否注意到,call方法没有修饰符,那么这个方法就是默认的,他的访问权限是包,后面会学到。
我们需要注意几个问题:
1.子类访问权限要小与夫类。2.super和this不同并不代表当前对象。他只能用于调用父类的方法。不要搞混了。