多态polymorphism:方法或者对象具有多种形态
代码示例
// 通过方法重载,展现同一种方法的不同形态 public class PolyMethod { public static void main(String[] args) { AA aa = new AA(); aa.f(); aa.f(1); aa.f(1, 2); } } class AA { public void f() { System.out.println("f()"); } public void f(int i) { System.out.println("f(i)"); } public void f(int i, int j) { System.out.println("f(i,j)"); } }
代码示例
// 通过子类继承父类并重写父类中的方法,体现同一个方法的不同形态 public class PolyMethod02 { public static void main(String[] args) { BB bb = new BB(); bb.f(); BBB bbb = new BBB(); bbb.f(); } } class BB { public void f() { System.out.println("BB f()"); } } class BBB extends BB { @Override public void f() { System.out.println("BBB f()"); } }
代码示例
public class PolyObject { public static void main(String[] args) { People people = new Student(); //people编译类型为People,运行类型为Student //System.out.println(people.id); //people.f2(); System.out.println("name=" + people.name); System.out.println(people.show()); } } class People { String name = "jack"; int age = 18; public void f1() { System.out.println("People f1()"); } public String show() { return "name=" + name + ",age=" + age; } } class Student extends People { int id = 1; double score = 100; @Override public String show() { return super.show() + ",id=" + id + ",score=" + score; } public void f2() { System.out.println("Student f2()"); } }
代码示例
public class PolyDetail02 { public static void main(String[] args) { A a = new B(); System.out.println(a.count); //System.out.println(a.x); } } class A{ int count = 10; } class B extends A{ int count = 20; int x = 100; }
代码示例
public class PolyDetail03 { public static void main(String[] args) { C c = new D(); System.out.println(c instanceof C); System.out.println(c instanceof D); System.out.println(c instanceof Object); D d = new D(); System.out.println(d instanceof C); System.out.println(d instanceof D); C cc = new C(); System.out.println(cc instanceof C); System.out.println(cc instanceof D); } } class C {} class D extends C {}
代码示例
public class DynamicBinding { public static void main(String[] args) { A a = new B(); System.out.println(a.sum()); System.out.println(a.sum1()); } } class A { public int i = 10; public int sum() { return getI() + 10; } public int sum1() { return i + 10; } public int getI() { return i; } } class B extends A { public int i = 20; @Override public int sum() { return getI() + 20; } @Override public int sum1() { return i + 10; } @Override public int getI() { return i; } }