Java继承和多态之子类继承性
Rectangle.java
/**
* 任务:定义一个矩形 Rectangle 类,继承 Shape 类,
* 在这个类中分别定义一个名为 area 的方法,实现计算该形状面积的功能。
* 类名为:Rectangle
*/
class Rectangle extends Shape{//class 子类 extends 父类
double area(){ // 计算矩形面积的功能。
double a = super.getHeight();//get用来赋值,set用来获取值
double b = super.getWidth();
//super.(A) super可以访问父类的①构造方法;②成员变量;③成员方法
return a * b;
}
}
Shape.java
public class Shape { //目标父类
private double height; //高
private double width; // 底边
//构造
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
}
Triangle.java
/**
* 任务:定义一个三角形 Triangle 类,继承 Shape 类,
* 在这个类中分别定义一个名为 area 的方法,实现计算该形状面积的功能。
* 类名为:Triangle
*/
// 定义一个Triangle的公开类,并继承Shape类
class Triangle extends Shape{
double area(){
double a = super.getHeight();
double b = super.getWidth();
return 0.5*a * b;
}
}
Test.java
public class Test {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();//构造
rectangle.setHeight(30);//赋值
rectangle.setWidth(20);
Triangle triangle = new Triangle();
triangle.setHeight(10);
triangle.setWidth(15);
System.out.printf("矩形的面积:%.2f\n三角形的面积为%.2f",rectangle.area(),triangle.area());
}
}
Java继承和多态之方法重写
Demo
(小样例)
public class Demo {
public static void main(String[] args) {
Sphere sphere = new Sphere(20.0);
double s = sphere.area();
System.out.printf("球的表面积为:%.2f", s);
}
}
Sphere
/**
* 重写 Shape 中的 area 方法,计算球的表面积。
*/
class Shape {
private double r; //球的半径
// 球的体积3/4*π*r^3
public double area(){
double s = (double)3/4*Math.PI*Math.pow(r,3);
return s;
}
}
public class Sphere extends Shape{
private double r; //球的半径
public Sphere(double r) {//有参构造
this.r = r;
}
// 重写 Shape 中的 area 方法,计算球的表面积(4πr^2),将计算结果返回
public double area(){
double s = (double)4 * Math.PI * Math.pow(r, 2);
//Math.pow(a, b) 表示次方 a^b
return s;
}
}
Java继承和多态之成员变量隐藏之优惠促销价格计算
Demo
public class Demo {
public static void main(String[] args) {
Seal seal = new Seal(0.7, 32.00);
System.out.println("商品打折后的价格为:"+seal.sealX());
System.out.println("商品原来的价格为:"+seal.getTotalMoney());
}
}
seal
/**
* 任务:计算商品打折后的价格
*/
class Total {
double totalMoney = 50.00;
public double getTotalMoney(){
return totalMoney;
}
}
// 定义一个Seal的公开类,并继承Total类
public class Seal extends Total{
double discount;//折扣
double totalMoney;//总价格
public Seal(double discount, double totalMoney){//有参构造
this.discount=discount;
this.totalMoney=totalMoney;
}
public double sealX(){//计算打折后的商品价格并返回
return totalMoney*discount;
}
}