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(); } }
【参考资料】