标签:
class Fruit{ void eat(){} } class Apple extends Fruit{ void eat(){} } class Test{ Fruit fruit = new Apple(); //------向上转型(父类引用指向子类对象) }
class Fruit{ void eat(){ System.out.println("Fruit eat"); } } class Apple extends Fruit{ void eat(){ System.out.println("Apple eat"); } } public class TestClass{ public static void main(String[] args){ Fruit fruit = new Apple(); fruit.eat(); //------动态绑定 } }output: Apple eat
class Fruit{ void eat(){ System.out.println("Fruit eat"); } } class Apple extends Fruit{ /* 重写父类方法,实现多态 */ void eat(){ System.out.println("Apple eat"); } } abstract class Car{ abstract void drive(); } class Volvo extends Car{ /* 实现父类(抽象类)方法,实现多态 */ void drive(){ System.out.println("Volvo drive"); } } public class TestClass{ public static void main(String[] args){ Fruit fruit = new Apple(); fruit.eat(); Car car = new Volvo(); car.drive(); } }output: Apple eat Volvo drive
interface People{ String sayName(); } class Lilei implements People{ /* 实现接口方法,实现多态 */ public String sayName(){ return "My name is Lilei"; } } class CreatePeople{ /* 匿名内部类也是实现接口多态的一种 */ public People getPeople(){ return new People() { @Override public String sayName() { return "My name is Wangfang"; } }; } } public class TestClass{ public static void main(String[] args){ People people1 = new Lilei(); People people2 = new CreatePeople().getPeople(); System.out.println(people1.sayName()); System.out.println(people2.sayName()); } }output: My name is Lilei My name is Wangfang
public class A { public String show(D obj) { return ("A and D"); } public String show(A obj) { return ("A and A"); } } public class B extends A{ public String show(B obj){ return ("B and B"); } public String show(A obj){ return ("B and A"); } } public class C extends B{ } public class D extends B{ } public class Test { public static void main(String[] args) { A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D(); System.out.println("1--" + a1.show(b)); System.out.println("2--" + a1.show(c)); System.out.println("3--" + a1.show(d)); System.out.println("4--" + a2.show(b)); System.out.println("5--" + a2.show(c)); System.out.println("6--" + a2.show(d)); System.out.println("7--" + b.show(b)); System.out.println("8--" + b.show(c)); System.out.println("9--" + b.show(d)); } }output: 1--A and A 2--A and A 3--A and D 4--B and A 5--B and A 6--A and D 7--B and B 8--B and B 9--A and D
标签:
原文地址:http://www.cnblogs.com/maying3010/p/5917972.html