Java 继承01

继承

●示例

class Person {
    public String name;

    Person(){
        System.out.println("Person Constrctor...");
    }
}


public class Husband extends Person{

    Husband(){
        System.out.println("Husband Constructor...");
    }
    
    public static void main(String[] args) {
        Husband husband  = new Husband();
    }
}

/*结果
 * Person Constrctor...
 * Husband Constructor...
 * 子类:Husband 继承 父类:Persion
*/
View Code

子类拥有父类的非private的属性、方法

问:私有属性和方法能不能被继承?答:不能,因为不能被调用。

子类可以拥有自己的属性和方法,即子类可以对父类进行扩展

在java中,类和类之间是单继承关系(一个类只能继承一个父类)

类 和 类 单继承

类 和 接口 多实现

接口 和 接口 多继承

继承的关键字:extends、implements

当一个类没有继承的两个关键字,则默认继承object  (java.lang.object)

public class Test{
    public static void main(String[] args) {
        System.out.println("---a---");
        Animal a = new Animal();
        System.out.println("---a2---");
        Animal a2 = new Animal("dog",888);
        System.out.println("---p---");
        Person p = new Person();
        System.out.println("---p2---");
        Person p2 = new Person("China", 666);
        System.out.println("-------");
        p.atcivity();
        //instanceof 判断对象是否是某个类的实例
        System.out.println(p instanceof Animal);
        System.out.println(p instanceof Person);
    }
}

class Animal{
    public int id;
    public String name;
    public int age;
    
    //如果父类构造器没有参数,则在子类的构造器中不需要使用 super 关键字调用父类构造器,系统会自动调用父类的无参构造器。
    Animal(){
        System.out.println("动物世界:Animal()");
    }
        
    //如果父类的构造器带有参数,则必须在子类的构造器中显式地通过 super 关键字调用父类的构造器并配以适当的参数列表。
    Animal(String name, int age){
        System.out.println("动物世界:Animal(String name, int age)" + name + "," + age);
    }
    
    void eat(){
        System.out.println("动物会吃食物");
    }
    
    //final类型的方法不能被子类重写
    final void run(){
        System.out.println("动物会活动");
    }
    
}

//子类继承父类
class Person extends Animal{
    //新增属性country
    public String country;
    
    //子类是不继承父类的构造器(构造方法或者构造函数)的,它只是调用(隐式或显式)。
    Person(){// 自动调用父类的无参数构造器
        System.out.println("人类的世界:Person()");
    }
    
    Person(String country, int age){
        super("China", 666);
        System.out.println("人类的世界:Person(String country, int age)"+ country + "," + age);
    }
    
    //重写父类的方法
    @Override    //添加这个注释  未报错  重写成功。
    void eat(){
        System.out.println("人类是杂食性动物");
    }
    
/*    报错,因为final类型的方法不能被子类重写
 * void run(){
        System.out.println("-------");
    }*/
    
    void atcivity(){
        super.run();
        super.eat();//super 指向父类的引用
        this.eat();//this 指向自己的引用
    }
}

 运行结果:

---a---
动物世界:Animal()
---a2---
动物世界:Animal(String name, int age)dog,888
---p---
动物世界:Animal()
人类的世界:Person()
---p2---
动物世界:Animal(String name, int age)China,666
人类的世界:Person(String country, int age)China,666
-------
动物会活动
动物会吃食物
人类是杂食性动物
true
true

原文地址:https://www.cnblogs.com/jszfy/p/12802540.html