Java继承

package pet;

public class Pet {
      private String name;
      private int health;
      private int love;//亲密度
      
      public Pet()
      {
        System.out.println("父类无参构造");
      }

  public Pet(String name, int health, int love) {
    System.out.println("父类3个参数的构造方法");
    this.name = name;
    this.health = health;
    this.love = love;
  }
  public void a()
  {
    System.out.println("测试子类重写");
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getHealth() {
    return health;
  }

  public void setHealth(int health) {
    this.health = health;
  }

  public int getLove() {
    return love;
  }

  public void setLove(int love) {
    this.love = love;
  }
  
      
}



package pet;

public class Dog extends Pet {

  // 真正的的无返回值的函数,构造函数
  // public Dog() {
  // System.out.println("dog的构造方法");
  // }
  private String strain;
  private String other;

  public Dog(String strain, String other) {// 有参构造函数//相当于setStrain()
    this.strain = strain;
    this.other = other;
  }

  public Dog() {
    // this("a","b");//调用含有两个参数的构造函数
    super("a", 2, 3);// 调用父类构造函数
    System.out.println("子类无参构造");
  }

  // 子类重写父类的方法:父类中已经存在了a(),子类又重写了一个a()
  public void a() {
    System.out.println("重写的子类dog");
  }

  public String getStrain() {
    return strain;
  }

  public void setStrain(String strain) {
    this.strain = strain;
  }

  public void print() {
    System.out.println("print.....");
    System.out.println(getName() + "\t" + getHealth() + "\t" + getLove() + "\t" + this.strain + "\t" + this.other);
       a();//先寻找当前类中的a(),如果没有再向父类中寻找
       this.a();//同上
       super.a();
  }

}


package pet;

public class TestPet {

  public static void main(String[] args) {
    Dog dog=new Dog();
    dog.setName("傻狗");
    dog.setHealth(99);
    dog.setLove(100);
    dog.setStrain("哈士奇");
    dog.print();
  }

}

 

上一篇:机器学习技法笔记(2)-Linear SVM


下一篇:Git的安装及其使用(一)