zoukankan      html  css  js  c++  java
  • JavaSE 基础 第32节 三大特性之继承

    2016-06-29

    1 继承概述
    父类、超类、基类
    子类、派生类

    Animal type skin legCount
    eat() huxi()

    Tiger run()
    Sheep

    extends只能继承一个类,Java不支持多重继承

    子类继承父类之后,子类可以调用父类的属性和方法,
    也可以重写父类的属性和方法,还可以增加自己的属性和方法。

    package com.java1995;
    /**
     * 父类、超类、基类:动物类
     * @author Administrator
     *
     */
    public class Animal {
        
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
        public String getSkin() {
            return skin;
        }
    
        public void setSkin(String skin) {
            this.skin = skin;
        }
    
        public int getLegCount() {
            return legCount;
        }
    
        public void setLegCount(int legCount) {
            this.legCount = legCount;
        }
    
        private String type;//类别
        private String skin;//肤色
        private int legCount;//几条腿
        
        public void eat(){
            System.out.println("动物在吃东西");
        }
        
        public void huxi(){
            System.out.println("动物在呼吸");
        }
    
    }
    package com.java1995;
    /**
     * 子类、派生类:羊
     * @author Administrator
     *
     */
    public class Sheep extends Animal {
        //方法重写、覆盖
        public void eat(){
            System.out.println("山羊在吃草");
        }
        
        public void fire(){
            System.out.println("山羊在打架");
        }
    
    }
    package com.java1995;
    /**
     * 子类、派生类:老虎
     * @author Administrator
     *
     */
    public class Tiger  extends Animal{
        
        //方法重写、覆盖
        public void eat(){
            System.out.println("老虎在吃东西");
        }
        
        public void run(){
            System.out.println("老虎在跑");
        }
    }
    package com.java1995;
    /**
     * 测试类
     * @author Administrator
     *
     */
    public class Test {
        
        public static void main(String[] args) {
            Tiger t=new Tiger();
            Animal a=new Tiger(); //多态
            t.eat();
            t.setType("老虎");
            t.setSkin("金黄色");
            t.setLegCount(4);
            System.out.println(t.getType()+","+t.getSkin()+","+t.getLegCount());
            
            t.run();
            
            Sheep s=new Sheep();
            s.eat();
            s.fire();
        }
    
    }

    【参考资料】

    [1] Java轻松入门经典教程【完整版】

  • 相关阅读:
    结对项目电梯调度--设计模拟
    程序的单元测试
    一个文本单词统计的案例
    MFC vs2012 Office2013 读写excel文件
    Unix NetWork Programming(unix环境编程)——环境搭建(解决unp.h等源码编译问题)
    VMware三种上网模型
    矩阵求逆算法及程序实现(C++)
    unix环境高级编程基础知识之第四章
    2014阿里研发面试题目
    MFC下debug改成release版本出现问题及解决办法
  • 原文地址:https://www.cnblogs.com/cenliang/p/5627482.html
Copyright © 2011-2022 走看看