1.super理解为父类的
2.super可以用来调用属性、方法、构造器
3.super的使用
* ①我们可以在子类的方法或构造器中通过使用“super.属性”、“super.方法”的方式,显示调用
* ②特殊情况:当子类和父类定义了同名的属性时,我们要想在子类中调用父类中声明的属性,
* 则必须显示的使用“super.属性”的方式,表明调用的是父类中声明的属性。
* 子类重写了父类的方法以后,我们想在子类中调用父类中被重写的方法时,
* 则必须显式使用“super.方法”的方式,表示调用的是父类中被重写的方法。
*4.super调用构造器
* ①我们可以在子类构造器中显式的使用“super(形参列表)”的方式,调用父类中声明的指定构造器
* ②“super(形参列表)”的使用,必须声明在子类构造器中的首行
* ③在构造器的首行没有显式的声明“this(形参列表)”或“super(形参列表)”,则默认调用的是父类中空参的构造方法,super();
public class SuperTest {
public static void main(String[] args) {
Student2 student2=new Student2();
student2.show();
}
}
class Person2{
String name;
int age;
int id=100;
public Person2() {
}
public Person2(String name, int age) {
this.name = name;
this.age = age;
}
public void eat()
{
System.out.println("父类的方法eat()");
}
}
class Student2 extends Person2{
int id=200;
@Override
public void eat() {
System.out.println("子类重写的方法eat()");
}
//这里想调用父类的eat()方法
public void eat2()
{
//eat();
super.eat();
}
public void show()
{
//调用子类的id 200
System.out.println("id="+id);
//调用父类的id 100
System.out.println("id="+super.id);
}
}
/**
* super调用构造器
* ①我们可以在子类构造器中显式的使用“super(形参列表)”的方式,调用父类中声明的指定构造器
* ②“super(形参列表)”的使用,必须声明在子类构造器中的首行
* ③在构造器的首行没有显式的声明“this(形参列表)”或“super(形参列表)”,则默认调用的是父类中空参的构造方法,super();
* @author orz
*/
public class SuperTest {
public static void main(String[] args) {
Student3 s1=new Student3();
System.out.println();
Student3 s2=new Student3("IT");
System.out.println();
Student3 s3=new Student3(12,"张三","IT");
}
}
class Person3{
int age;
String name;
Person3()
{
System.out.println("父类空参构造器");
}
Person3(int age, String name) {
this.age = age;
this.name = name;
}
}
class Student3 extends Person3{
String job;
public Student3() {
System.out.println("子类空参构造器");
}
public Student3(String job) {
this.job = job;
System.out.println("子类带一参数构造器");
}
public Student3(int age,String name,String job)
{
super(age,name);
this.job=job;
System.out.println("子类带三个参数的构造器");
}
}