继承

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

  • 子类使用父类的public protected属性,方法相当与没写
    package com.example.demo;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
            Animal animal=new Animal();
            animal.update();
            Cat cat=new Cat();
            cat.add(new heart(),animal);
            Animal dog=new Dog(new  heart());
            Animal dog1=new Dog(new  heart());
            dog.toString();
            animal.update();
    
        }
    
    
    }
    class heart{
        protected String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "heart{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
    class Animal {
        public List<heart>  hearts= new ArrayList<heart>();
    
    
    
    
    
        @Override
        public String toString() {
            return "Animal{" +
                    "hearts=" + hearts +
                    '}';
        }
        public void update(){
    
            System.out.println(hearts.toString());
            for (heart heart:hearts) System.out.println(heart.getName());
        }
    }
    
    class Cat  {
    
    
        public void add(heart heart,Animal a){
            heart.setName("cay");
            a.hearts.add(heart);
            System.out.println(heart.name);
            System.out.println(a.hearts.toString());
        }
    
    }
    class Dog extends Animal{
        public Dog(heart heart) {
            super();
            heart.setName("dog");
            hearts.add(heart);
            toString();
        }
    
    }

    []
    cay
    [heart{name='cay'}]
    [heart{name='cay'}]
    cay

上一篇:Java-面向对象的三大特征--多态


下一篇:python面向对象多态与多态性