1.super调用父类构造方法且必须出现在方法内第一行
2.super必须只能出现在子类的方法或者构造方法中
3.super和this不能同时存在
vs this:
代表的对象不同:
this:本身
super:父类
前提:
this:没有继续也可以使用
super:只能在继承后使用
构造方法
this()本类构造
super()父类构造
package com.wuming.oop3.demo06; //person 人 父类 public class Person {protected String name="无名";/* public Person() {System.out.println("person无参执行了");}*/public Person(String name) {System.out.println("person无参执行了");}public void print(){//把public 改成private报错,Error:(20, 14) java: print()可以在com.wuming.oop3.demo06.Person中访问privateSystem.out.println("person");} }
package com.wuming.oop3.demo06;//学生 is 人 子类 //子类继承父类就拥有父类的全部方法 public class Student extends Person {public Student() {//1 父类无参//默认隐藏了super(),调用父类无参构造且必须在大括号第一行//this("d"); 和super()都必须在大括号第一行,只能用一个//默认都不写//2父类有参super("s");//如果父类只写了有参,子类会报错,加上super("参数")就ok;默认调用父类无参System.out.println("Student无参执行了");}public Student(String name) {super("dd");this.name = name;}private String name="wuming";public void test(String name){System.out.println(name);//wmSystem.out.println(this.name);//wumingSystem.out.println(super.name);//无名}public void print(){System.out.println("student");}public void test1(){print();//studentthis.print();//studentsuper.print();//person} }
package com.wuming.oop3;import com.wuming.oop2.demo05.Person; import com.wuming.oop3.demo06.Student; public class Application {public static void main(String[] args) {Student student = new Student();student.test("wm");student.test1();Student student1 = new Student();//先执行 person无参执行了 Student无参执行了 默认隐藏了super()} }
person无参执行了
Student无参执行了
wm
wuming
无名
student
student
person
person无参执行了
Student无参执行了