zoukankan      html  css  js  c++  java
  • day6_test1_inheritance

    类图

    代码

    Pet类

    package org.lanqiao.com;
    
    public class Pet {
        private String name ;
        private String sex;
        private String kind;
        private int age;
    
        {
            this.name = "未命名";
        }
    
        public Pet(String kind) {
            this.kind =kind;
        }
    
        protected void eat(String food) {
            System.out.println(this.name + "正在吃" + food);
        }
    
        protected String bark() {
            return name +"在叫";
        }
    
        protected void sleep() {
            System.out.println(name + "正在睡觉");
        }
    
        protected void setName(String name) {
            this.name = name;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
        public String getSex() {
            return sex;
        }
        public String getKind() {
            return kind;
        }
        public int getAge() {
            return age;
        }
    }
    
    

    Cat类:

    package org.lanqiao.com;
    
    public class Cat extends Pet{
    
    	public Cat(String kind) {
    		super(kind);
    	}
    
    	@Override
    	protected String bark() {
    		return super.bark() + "喵喵";
    	}
    
    	public void catchMouse() {
    		System.out.println(this.getName() + "在抓老鼠");
    	}
    }
    
    

    Dog类:

    package org.lanqiao.com;
    
    public class Dog extends Pet {
    
    	public Dog(String kind) {
    		super(kind);
    	}
    	protected void watchHome() {
    		System.out.println(getName() +"正在看家");
    	}
    	@Override
    	protected String bark() {
    		return getName() +"正在叫:汪汪";
    	}
    }
    
    

    Master类:

    package org.lanqiao.com;
    
    public class Master {
    	public static void main(String[] args) {
    		Pet dog = new Dog("哈士奇");
    		dog.setName("奥特曼");
    		dog.eat("骨头");
    		System.out.println(dog.bark());
    		((Dog)dog).watchHome();
    		System.out.println(dog.bark());
    		Pet pet = new Pet("wu");
    
    		Pet cat = new Cat("狸花猫");
    		cat.setName("小怪兽");
    		Master master =new Master();
    		master.feed(cat);
    
    	}
    
    	public void feed(Pet pet) {
    		pet.bark();
    		if(pet instanceof Dog){
    			((Dog)pet).eat("骨头");
    		}else{
    			((Cat)pet).eat("鱼");
    		}
    	}
    }
    
    
    

    运行结果:

  • 相关阅读:
    Java基础知识强化之IO流笔记39:字符流缓冲流之复制文本文件案例01
    阿里云服务器绕过25端口发邮件
    springboot在lunix后台启动,退出账号也不关闭
    创建Maven项目出错 pom出错
    corn表达式 经典
    开发微信公众号基本配置参数错误
    Spring与ActiveMQ整合
    log4j.properties 打印到控制台 写法
    如何在spring环境中做单元测试
    添加jar包到本地Maven仓库
  • 原文地址:https://www.cnblogs.com/zzz1zzz/p/14268697.html
Copyright © 2011-2022 走看看