super详解
1.super与this 的区别:
```java
package com.zishi.oop.demo05;
public class Application {
public static void main(String[] args) {
// Student student = new Student();
// student.say();
Student student = new Student();
student.test("一只肥");
}
}
```
```java
package com.zishi.oop.demo05;
//在Java中,所有的类,都默认直接或者间接继承Object
//CTRL + H 查看
//父类 (基类)
public class Person {
//public
//protected
//default
//private
/*
int money = 10_0000_0000;
public void say(){
System.out.println("说了一句话");
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
*/
protected String name = "yizhifei";
}
```
```java
package com.zishi.oop.demo05;
//子类 (派生类)
public class Student extends Person{
private String name = "两只肥";
public void test(String name){
System.out.println(name); //传参 一只肥
System.out.println(this.name); //这个类定义的参数 两只肥
System.out.println(super.name); //父类 yizhifei
}
}
```
2.public中 super和this 的区别
```java
package com.zishi.oop.demo05;
public class Application {
public static void main(String[] args) {
// Student student = new Student();
// student.say();
Student student = new Student();
//student.test("一只肥");
student.test2();
}
}
```
```java
package com.zishi.oop.demo05;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
public class Person {
public void print(){
System.out.println("Person");
}
}
```
```java
package com.zishi.oop.demo05;
//子类 (派生类)
public class Student extends Person{
private String name = "两只肥";
public void print(){
System.out.println("Student");
}
public void test2(){
print(); //Studnt
this.print(); //Studnt
super.print(); //Person
}
}
```
3.构造器调用
```java
public Person() {
System.out.println("Person无参执行了");
}
```
```java
public Student() {
//隐藏代码:调用了父类的无参构造 super()
super();//调用了父类的构造器,必须要在子类构造器的第一行
System.out.println("Student无参执行了");
}
```
构造器只能调用一个 ,有参或无参
有参:
this();//也只能放在子类构造器的第一行
4.调用父类有参构造
当父类使用有参构造时,子类无法使用无参构造,但可以调用父类的有参构造
总结:
```java
super注意点:
1. super调用父类的构造方法,必须在构造方法的第一个
2. super必须只能出现在子类的方法或者构造方法中!
3. super和 this 不能同时调用构造方法!
Vs this:
代表的对象不同:
this:本身调用者这个对象super:代表父类对象的应用前提
this:没有继承也可以使用
super:只能在继承条件才可以使用构造方法
this(;本类的构造super():父类的构造!
```