super的使用

关于Super()的用法
1.Super()只能用在子类的构造方法中使用,在其它地方使用存在编译错误。
2.super()构造的父类只有在子类中有效,离开子类无法使用。
3.super.的调用的是由在子类构造的时候使用了super()的无参或者有参构造出来的父类。
4.当父类为有参构造而不写无参构造的时候,我们子类构造方法必须拥有父类的构造方法就需要用Super(String xx,int no)的构造方法将把父类构造出来才能继续构造子类。

public class Main{
  public static void main(String[] args) {
    Cat c1 = new Cat(3);
    System.out.println( ",年龄:" + c1.getage());
  }
}
class Animal {
  int age;
Animal(int age){
  this.age=age;
}
  public void setAge(int age) {
    this.age = age;
  }
  **public Animal() {
  }**//如果不存在无参构造报错。
  public int getAge() {
    return age;
  }
}
class Cat extends Animal{
  private int age;
  public void setage(int age) {
    this.age = age;
  }
  public int getage() {
   age=super.getAge();//调用的是无惨构造出来的
    return age;
  }
  public Cat() {
  }
  public Cat(int age) {
    this.age = age;
  }
}

5.当存在子类没有重写父类的方法时候,此时使用this.与super. 的结果相同如以下代码。

class People{
    private String name;
    public People( String name) {
this.name = name;
    }
    public String getName() {
        return name;
    }
}

class Student extends People{

    public Student(String name) {
super(name);
   
    }
    public String toString(){
        return ("(Name:" + super.getName())//可以替换成this.getName()0
             

}}
public class Main {
    public static void main(String[] args) {
        Student zs = new Student("370202X");
        System.out.println(zs);

    }
}

你可能感兴趣的:(语言中的一些基础概念,java)