zoukankan      html  css  js  c++  java
  • Java(14):继承

    package zzz;
    
    // 创建继承
    
    public class Demo2 {
        
        public static void main(String[] args) {
            
            Animal animal = new Animal();
            animal.live();
            animal.run();
            
            System.out.println("******************************************");
            
            Cat catAnimal = new Cat();
            catAnimal.live();
            catAnimal.run();
            
            System.out.println("******************************************");
            
            SmallCat smallCat = new SmallCat();
            smallCat.run();
            smallCat.live();
            
            System.out.println("******************************************");
            
            Dog dog = new Dog();
            dog.run();
    
        }
        
    }
    
    
    class Animal {
        
        String animal = "animal";
        
        public Animal() {
            System.out.println("父类构造函数Animal结束.");
        }
        public void live() {
            System.out.println(animal+" live ...");
        }
        public void run() {
            System.out.println(animal + " can run ...");
        }
    }
    
    class Dog extends Animal {
        String animal = "dog";
        
        public Dog() {
            System.out.println("Dog() end.");
        }
        @Override
        public void run() {
            System.out.println(super.animal + " can run, " + this.animal + " can run ...");
        }
    }
    
    class Cat extends Animal {
    
        String animal = "cat";
        
        public Cat() {
    //        调用父类的构造函数
            super();
            System.out.println("子类构造函数Cat结束.");
        }
    
        @Override
        public void run() {
            System.out.println(super.animal + " can run, such as " + this.animal);
        }
        @Override
        public void live() {
    //        子类调用父类的方法
            super.live();
        }
    }
    
    class SmallCat extends Cat {
    
        String animal = "small cat";
        
        public SmallCat() {
    //        继承子类默认会调用父类的无参构造函数,隐式存在一个super();调用父类Cat类的构造函数
            System.out.println("子类构造函数SmallCat结束.");
        }
        @Override
        public void run() {
            System.out.println(this.animal + " can run .");
        }
        @Override
        public void live() {
            super.live();
        }
    }
  • 相关阅读:
    继承String?
    java sizeof
    什么是java序列化,如何实现java序列化?
    负载均衡的时候如何实现相同的session被分配到同一个服务器
    如何实现session共享
    java 字符串排序
    forward和redirect的区别
    数字签名 数字证书
    找出数组中重复次数最多的元素并打印
    get和post区别
  • 原文地址:https://www.cnblogs.com/kenantongxue/p/14014054.html
Copyright © 2011-2022 走看看