通过实例学习Java继承

一、新建Animal基类

public abstract class Animal {
 protected int legs;
 protected Animal(int legs){
  this.legs = legs;
 }
 public Animal(){}
 public void walk(){}
 public void eat(){}
}

二、新建Pet Interface

public interface Pet {
 public String getName();;
 public void setName(String name);
 public void play();
}

三、用三个子类来实现Animal和Pet

 


public class TestDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Spider spider = new Spider();
  Cat cat = new Cat();
  Fish fish = new Fish();
  spider.eat();
  cat.eat();
  cat.play();
  fish.eat();
 }

}

五、结果

I don't know what spider eat.
Cat like eat meat.
Cat like play ball.
I don't know what fish eat.
public class Cat extends Animal implements Pet {
 private String name;
 public Cat(){
  super(4);
 }
 public Cat(String name){
  this.name = name;
 }
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
 }
 public void play(){
  System.out.println("Cat like play ball.");
 }
 public void eat(){
  System.out.println("Cat like eat meat.");
 }
}

 


public class Fish extends Animal implements Pet {
 private String name;
 public Fish(){
  super(0);
 }
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
 }
 public void play(){
  System.out.println("Fish like play water.");
 }
 public void eat(){
  System.out.println("I don't know what fish eat.");
 }
 public void walk(){
  System.out.println("Fish can't walk if no water.");
 }
}


public class Spider extends Animal{

 public Spider(){
  super(4);
 }
 public void eat(){
  System.out.println("I don't know what spider eat.");
 }
}

 

四、测试