Animal animal = new Tiger;多态的理解

Animal animal = new Tiger(); 

Animal:animal的类型;

animal:Tiger类实例的引用,类型为Animal的变量;

new Tiger;Tiger类实例

=  后面赋值给前面

 

 

理解可拆分为:

Tiger tiger;        //声明变量

tiger= new Tiger();        //创建对象变量初始化

Animal animal;        //声明变量

animal = tiger;        //初始化(赋值)  

如果Tiger有对Animal重写的方法,animal调用的是tiger重写过的方法;

 

public class Main {
    public static void main(String[] args) {
        Animal tiger = new Tiger();

//结果为“animal”
        System.out.println("name = " + tiger.name);
        Tiger tiger1 = new Tiger();
        System.out.println("name = " + tiger1.name);


        Tiger tiger2;
        tiger2 = new Tiger();
        Animal animal;
        animal = tiger2;
        System.out.println(animal.name + new Tiger().name);
    }
}
//
public class Animal {


    String name = "animal";

    public void eat() {
        System.out.println("动物吃东西!");
    }
}
//

public class Tiger extends Animal {
         String name = "tiger";

    @Override
        public void eat() {
            System.out.println("虎吃鸡!");
        }

        public void run() {
            System.out.println("虎奔跑!");
        }
    }
/
public class Snake extends Animal {
    public String name = "snake";

    @Override
    public void eat() {
        System.out.println("蛇吞象!");
    }

    public void run() {
        System.out.println("蛇爬行!");
    }
}

 

 

你可能感兴趣的:(java,开发语言)