标签:
1. 动态绑定public class Shapes { private static RandomShapeGenerator gen = new RandomShapeGenerator(); public static void main(String[] args) { Shape[] shapeArr = new Shape[9]; // 填充数组 for (int i = 0; i < shapeArr.length; i++){ shapeArr[i] = gen.next(); } // 动态调用方法 for (Shape shape : shapeArr){ shape.draw(); } } } class RandomShapeGenerator { private Random rand = new Random(47); public Shape next() { switch (rand.nextInt(3)) { default: case 0: return new Circle(); case 1: return new Square(); case 2: return new Triangle(); } } } class Shape { public void draw() { System.out.println("Shape.draw()"); } public void erase() { System.out.println("Shape.erase()"); } } class Circle extends Shape { public void draw() { System.out.println("Circle.draw()"); } public void erase() { System.out.println("Circle.erase()"); } } class Triangle extends Shape { public void draw() { System.out.println("Triangle.draw()"); } public void erase() { System.out.println("Triangle.erase()"); } } class Square extends Shape { public void draw() { System.out.println("Square.draw()"); } public void erase() { System.out.println("Square.erase()"); } } /* Output: Triangle.draw() Triangle.draw() Square.draw() Triangle.draw() Square.draw() Triangle.draw() Square.draw() Triangle.draw() Circle.draw() *///:~
public class PrivateOverride { private void f() { print("private f()"); } public static void main(String[] args) { PrivateOverride po = new Derived(); po.f(); } } class Derived extends PrivateOverride { public void f() { print("public f()"); } } /* Output: private f() *///:~
class Meal { Meal() { print("Meal()"); } } class Bread { Bread() { print("Bread()"); } } class Cheese { Cheese() { print("Cheese()"); } } class Lettuce { Lettuce() { print("Lettuce()"); } } class Lunch extends Meal { Lunch() { print("Lunch()"); } } class PortableLunch extends Lunch { PortableLunch() { print("PortableLunch()"); } } public class Sandwich extends PortableLunch { private Bread bread = new Bread(); private Cheese cheese = new Cheese(); private Lettuce lettuce = new Lettuce(); public Sandwich() { print("Sandwich()"); } public static void main(String[] args) { new Sandwich(); } } /* Output: Meal() Lunch() PortableLunch() Bread() Cheese() Lettuce() Sandwich()
class Glyph { void draw() { print("Glyph.draw()"); } Glyph() { print("Glyph() before draw()"); this.draw(); print("Glyph() after draw()"); } } class RoundGlyph extends Glyph { private int radius = 1; RoundGlyph(int r) { radius = r; print("RoundGlyph.RoundGlyph(), radius = " + radius); } void draw() { print("RoundGlyph.draw(), radius = " + radius); } } public class PolyConstructors { public static void main(String[] args) { new RoundGlyph(5); } } /* Output: Glyph() before draw() RoundGlyph.draw(), radius = 0 Glyph() after draw() RoundGlyph.RoundGlyph(), radius = 5 *///:~
之所以调用的是子类的draw方法,this的含义是谁调用我,this指向的就是谁,Glyph构造器是通过RoundGlyph类构造器中super()方法触发,所以this指向的是RoundGlyph中的draw方法
标签:
原文地址:http://blog.csdn.net/zdp072/article/details/43058439