day09--抽象类的练习
This commit is contained in:
20
day09/src/com/inmind/abstract06/test/Circle.java
Normal file
20
day09/src/com/inmind/abstract06/test/Circle.java
Normal file
@@ -0,0 +1,20 @@
|
||||
package com.inmind.abstract06.test;
|
||||
|
||||
|
||||
public class Circle extends Shape {
|
||||
|
||||
//定义一个有参构造,必须要求传入半径,交给父类来管理
|
||||
public Circle(int r){
|
||||
super(0,0,r);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getArea() {
|
||||
return Math.PI*getR()*getR();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getZC() {
|
||||
return 2*Math.PI*getR();
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,15 @@ package com.inmind.abstract06.test;
|
||||
*/
|
||||
public class Demo09 {
|
||||
public static void main(String[] args) {
|
||||
//创建一个长方形对象
|
||||
Rectangle rectangle = new Rectangle(4,2);
|
||||
System.out.println("长方形的面积:"+rectangle.getArea());
|
||||
System.out.println("长方形的周长:"+rectangle.getZC());
|
||||
//创建一个圆形对象
|
||||
Circle circle = new Circle(2);
|
||||
System.out.println("圆形的面积:"+circle.getArea());
|
||||
System.out.println("圆形的周长:"+circle.getZC());
|
||||
|
||||
//如何快速定义出一个正方型的类,还不用自己实现周长和面积的方法
|
||||
}
|
||||
}
|
||||
|
||||
19
day09/src/com/inmind/abstract06/test/Rectangle.java
Normal file
19
day09/src/com/inmind/abstract06/test/Rectangle.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package com.inmind.abstract06.test;
|
||||
|
||||
public class Rectangle extends Shape{
|
||||
|
||||
//定义一个有参构造,必须要求传入长宽,交给父类来管理
|
||||
public Rectangle(int chang,int kuan){
|
||||
super(chang,kuan,0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getArea() {
|
||||
return getChang()*getKuan();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getZC() {
|
||||
return (getChang()+getKuan())*2;
|
||||
}
|
||||
}
|
||||
46
day09/src/com/inmind/abstract06/test/Shape.java
Normal file
46
day09/src/com/inmind/abstract06/test/Shape.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package com.inmind.abstract06.test;
|
||||
|
||||
public abstract class Shape {
|
||||
//定义共性的属性:涵盖大部分形状的属性
|
||||
private int chang;//矩形的长
|
||||
private int kuan;//矩形的宽
|
||||
private int r;//圆的半径
|
||||
|
||||
//满参构造:创建对象,对属性进行赋值
|
||||
public Shape(int chang, int kuan, int r) {
|
||||
this.chang = chang;
|
||||
this.kuan = kuan;
|
||||
this.r = r;
|
||||
}
|
||||
|
||||
//提供get/set方法,对私有的属性进行操作
|
||||
public int getChang() {
|
||||
return chang;
|
||||
}
|
||||
|
||||
public void setChang(int chang) {
|
||||
this.chang = chang;
|
||||
}
|
||||
|
||||
public int getKuan() {
|
||||
return kuan;
|
||||
}
|
||||
|
||||
public void setKuan(int kuan) {
|
||||
this.kuan = kuan;
|
||||
}
|
||||
|
||||
public int getR() {
|
||||
return r;
|
||||
}
|
||||
|
||||
public void setR(int r) {
|
||||
this.r = r;
|
||||
}
|
||||
|
||||
//计算面积的方法
|
||||
public abstract double getArea();
|
||||
//计算周长的方法
|
||||
public abstract double getZC();
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user