package com.tarena.day09.shape; public class Point { public int x; public int y; public Point() { super(); } public Point(int x, int y) { super(); this.x = x; this.y = y; } } package com.tarena.day09.shape; public class ShapeDemp { /** * @param args */ public static void main(String[] args) { Circle c = new Circle(3,4,5); System.out.println(c.area()); Shape s = c;//圆的实例也是图形的实例 System.out.println(s.area()); //s.area() 是在Shape 上声明的,但是被Circle覆盖了 //java在执行期间确定最终的方法。由实际的对象决定最终的方法(方法的动态绑定)。 s = new Rectangle(2,3,4,5); System.out.println(s.area()); Shape[] ss = {new Circle(1,2,4),new Rectangle(1,2,3,4)}; //print(ss[0]); //print(ss[1]); Shape x =c; check(x); } public static void print(Shape s) { System.out.println(s.area()); } public static void check(Shape s) { if(s instanceof Circle) { Circle c = (Circle)s; System.out.println("是圆形"+c.getR()); } } } package com.tarena.day09; public class ConstructorsDemo { public static void main(String[] args) { Koo koo = new Koo(); //koo先 System.out.println(koo.a); } } class Goo{ int a; public Goo(int a) { this.a = a; } } //class Koo extends Goo{}//错,子类默认调用父类无参数构造器 class Koo extends Goo{ int b; public Koo() { //super() 必须写在第一行,与this()互斥 super(1);//super()调用复类构造器 //子类一定调用父类构造器 } } package com.tarena.day09.shape; public class Shape { public double area() { return 0; } } package com.tarena.day09.shape; public class Rectangle extends Shape { private Point p; private int width; private int height; public Rectangle() { super(); } public Rectangle(int x,int y,int width, int height) { super(); p = new Point(x,y); this.width = width; this.height = height; } @Override public double area() { return width * height; } } package com.tarena.day09.shape; public class Circle extends Shape{ private Point center; private int r; public Circle() {} public Circle(int x,int y,int r) { this.center = new Point(x,y); this.r = r; } public Point getCenter() { return center; } public void setCenter(Point center) { this.center = center; } public int getR() { return r; } public void setR(int r) { this.r = r; } public double area() { return Math.PI *r*r; } }