类的继承

public class 子类 extends 父类 {
}

子类可以重写父类的方法,但也可以通过【super.父类的方法】调用父类的方法。通过【super.父类的属性】调用父类的属性。

class Computer3 { // 父类:电脑
    String sayHello() { // 方法:打招呼
        return "欢迎使用";
    }
}

public class Pad3 extends Computer3 { // 子类:平板电脑
    String sayHello() { // 子类重写父类方法
        return super.sayHello() + "iPad"; // 调用父类方法并添加字符串
    }

    public static void main(String[] args) {
        Computer3 pc = new Computer3(); // 创建父类-电脑类对象
        System.out.println(pc.sayHello());

        Pad3 ipad = new Pad3(); // 创建子类-平板电脑类对象
        System.out.println(ipad.sayHello());
    }
}

object类

public class Hello {
    public String getStr(){
        return (getClass().getName());
    }
    
    @Override 
    public String toString(){
        return (getClass().getName()+"。");
    }



    public static void main(String[] args) {
        Hello ho = new Hello();

        System.out.println("ho.getStr():"+ho.getStr());

        System.out.println("ho.toString():"+ho.toString());

    }
}

        /*ho.getStr():Hello
        ho.toString():Hello。*/

 

疑问

class Animal {
    String branch;

    public Animal(String branch) {
        this.branch = branch;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    @Override
    public boolean equals(Object obj) {
        Animal animal = (Animal) obj;
        if (this.getBranch().equals(animal.getBranch())) {
            return true;
        } else {
            //System.out.println(this.getBranch()); ——→ 输出“猪科”
            //System.out.println(animal.getBranch()); ——→ 输出“犬科”
            return false;
        }
    }
}

class NewDog extends Animal {
    public NewDog(String branch) {
        super(branch);
    }
}

class NewPig extends Animal {
    public NewPig(String branch) {
        super(branch);
    }
}

public class RightResult {
    public static void main(String[] args) {
        NewPig pig = new NewPig("猪科");
        NewDog dog = new NewDog("犬科");
        if (pig.equals(dog)) {
            System.out.println("猪和狗是同类!!!");
        } else {
            System.out.println("猪和狗不是同类。");
        }
    }
}

 

 

posted on 2022-07-12 21:04  jxba  阅读(53)  评论(0编辑  收藏  举报