1 package com.lagou.task09;
2
3 public class Shape {
4 private int x;
5 private int y;
6
7 public Shape() {
8 }
9
10 public Shape(int x, int y) {
11 setX(x);
12 setY(y);
13 }
14
15 public int getX() {
16 return x;
17 }
18
19 public void setX(int x) {
20 this.x = x;
21 }
22
23 public int getY() {
24 return y;
25 }
26
27 public void setY(int y) {
28 this.y = y;
29 }
30
31 public void show() {
32 System.out.println("横坐标:" + getX() + ",纵坐标:" + getY());
33 }
34
35 // 自定义静态方法
36 public static void test() {
37 System.out.println("Shape类中的静态方法!");
38 }
39 }
1 package com.lagou.task09;
2
3 public class Rect extends Shape {
4 private int len;
5 private int wid;
6
7 public Rect() {
8 }
9
10 public Rect(int x, int y, int len, int wid) {
11 super(x, y);
12 setLen(len);
13 setWid(wid);
14 }
15
16 public int getLen() {
17 return len;
18 }
19
20 public void setLen(int len) {
21 if(len > 0) {
22 this.len = len;
23 } else {
24 System.out.println("长度不合理哦!!!");
25 }
26 }
27
28 public int getWid() {
29 return wid;
30 }
31
32 public void setWid(int wid) {
33 if (wid > 0) {
34 this.wid = wid;
35 } else {
36 System.out.println("宽度不合理哦!!!");
37 }
38 }
39
40 @Override
41 public void show() {
42 super.show();
43 System.out.println("长度是:" + getLen() + ",宽度是:" + getWid());
44 }
45
46 // 自定义静态方法
47 //@Override Error: 历史原因、不是真正意义上的重写
48 public static void test() {
49 System.out.println("---Rect类中的静态方法!");
50 }
51 }
1 package com.lagou.task09;
2
3 public class Circle extends Shape {
4 private int ir;
5
6 public Circle() {
7 }
8
9 public Circle(int x, int y, int ir) {
10 super(x, y);
11 setIr(ir);
12 }
13
14 public int getIr() {
15 return ir;
16 }
17
18 public void setIr(int ir) {
19 if (ir > 0) {
20 this.ir = ir;
21 } else {
22 System.out.println("半径不合理哦!!!");
23 }
24 }
25
26 @Override
27 public void show() {
28 super.show();
29 System.out.println("半径是:" + getIr());
30 }
31 }
1 package com.lagou.task09;
2
3 public class ShapeTest {
4
5 // 自定义成员方法实现将参数指定矩形对象特征打印出来的行为,也就是绘制图形的行为
6 // Rect r = new Rect(1, 2, 3, 4);
7 // public static void draw(Rect r) {
8 // r.show(); // 1 2 3 4
9 // }
10 // 自定义成员方法实现将参数指定圆形对象特征打印出来的行为
11 // public static void draw(Circle c) {
12 // c.show(); // 5 6 7
13 // }
14 // 自定义成员方法实现既能打印矩形对象又能打印圆形对象的特征,对象由参数传入 子类 is a 父类
15 // Shape s = new Rect(1, 2, 3, 4); 父类类型的引用指向子类类型的对象,形成了多态
16 // Shape s = new Circle(5, 6, 7); 多态
17 // 多态的使用场合一:通过参数传递形成了多态
18 public static void draw(Shape s) {
19 // 编译阶段调用父类的版本,运行阶段调用子类重写以后的版本
20 s.show();
21 }
22
23 public static void main(String[] args) {
24
25 // Rect r = new Rect(1, 2, 3, 4);
26 // r.show();
27 ShapeTest.draw(new Rect(1, 2, 3, 4));
28 ShapeTest.draw(new Circle(5, 6, 7));
29 }
30 }