继承,多态..

“是一个”与“有一个”
继承关系 ,和拥有关系一定要搞清楚啊,兄弟。
IS A用测试继承关系 。这个是单向的。
例1、狗是动物,反过来不能成立,“动物是狗”不能成立,这就是单向。
例2、狗是狗,反过来还是“狗是狗”。这就是双向,这样就错了。

重载版的方法只是刚好有相同名字的不同方法 。

抽象类代表没有人能够创建出该类的实例。你还是可以使用抽象类来声明为引用类型给
多态使用。

抽象类除了被继承过之外,是没有用途,没有值,没有目的

如果你声明出一个抽象的方法,就必须将类也标记为抽象的。你不能在非抽象类中拥有抽象方法。

抽象的方法定义出一组子型共同的协议

把父类型作为方法的参数,就是一种多态。

抽象的方法没有内容,它只是为了标记出多态而存在。

一、现在一个动物类,分别 有dog ,wolf ,lion继承它。

package lhs.learn;

public abstract class Animal
{
    public String colour = "red";
    public void move()
    {
        System.out.println("I am move");
    }
    
    public void sound()
    {
        System.out.println("I am sound");
    }
    
    public abstract void eat();

}
package lhs.learn;

public class Dog extends Animal
{
    public void action()
    {
        System.out.println("忠诚!");
    }
    
    public void sound()
    {
        System.out.println("汪汪汪...");
    }
    
    public void eat()
    {
        System.out.println("吃骨头..");
    }

}





public class Wolf extends Animal
{
    public void action()
    {
        System.out.println("一群群的");
    }
    
    public void move()
    {
        System.out.println("I am fast move");
    }
    
    
    public void sound()
    {
        System.out.println("嗷呜嗷呜...");
    }
    
    public void eat()
    {
        System.out.println("吃兔子..");
    }

}






public class Lion extends Animal
{
    public void action()
    {
        System.out.println("狮子吼!");
    }
    
    public void sound()
    {
        System.out.println("吼吼吼吼..");
    }
    
    public void eat()
    {
        System.out.println("吃其它动物..");
    }

}

2、调用类。

package lhs.learn;

/*
 * 多态
 * 通过多态,你就可以编写出引进新型子类时也不必修改的程序。
 * 
 * */

public class Index
{
    
    public static void main(String[] args)
    {
        Animal[] animals = new Animal[3];
        animals[0] = new Dog();
        animals[1] = new Wolf();
        animals[2] = new Lion();
        
//        animals[0].move();
//        animals[1].move(); // 把子类当作总父类操作。
        
//        Wolf temp = (Wolf)animals[1];
//        temp.action();
        
        
        Index index = new Index();
        index.makeSound(new Dog());
        index.makeSound(new Wolf());
        
    }
    
    //以后不管增加多少动物鸡,鸭,鱼什么 的,这个方法 都不用改,因为它用了多态哦。
    public void makeSound(Animal animal)
    {
        animal.sound();
    }

}
原文地址:https://www.cnblogs.com/longhs/p/4257562.html