标题列举两个列子
###//父类:花 子类:樱花sakura
###//父类:球 子类:篮球
package com.gec.homework;
//举例两个继承的例子
//子类:樱花sakura
public class Sakura extends flower {
public static void main(String[] args) {
Sakura s = new Sakura();
// 子类调用父类属性
s.color = "粉红色";
// 子类调用父类方法
// s.setColor("白色");
s.setShape("五星形");
s.setSmell("薰衣草味");
//调用重写方法
s.bloom();
System.out.println(s.toString());
}
// 子类重写父类方法
public void bloom() {
String smell = "清淡味";
String shape = "椭圆卵形";
System.out.println("樱花开花啦,她的颜色是" + smell + " 形状是" + shape);
// 调用父类的方法
super.bloom();
}
}
//父类:花
class flower {
String color = "红色";
private String smell;
private String shape;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSmell() {
return smell;
}
public void setSmell(String smell) {
this.smell = smell;
}
public String getShape() {
return shape;
}
public void setShape(String shape) {
this.shape = shape;
}
public void bloom() {
System.out.println("春天到了,花儿开啦!!!" + "是" + color + "颜色的!");
}
@Override
public String toString() {
return "flower [color=" + color + ", smell=" + smell + ", shape=" + shape + "]";
}
}
package com.gec.homework;
//举例两个继承的例子
//父类:球
class ball {
int num = 1;
private int price ;
private int weight;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "ball [num=" + num + ", price=" + price + ", weight=" + weight + "]";
}
public void playBall() {
System.out.println("让我们一起去打球吧!");
}
public void totalprice() {
System.out.println("买球一共花了"+num * price+"元");
}
}
子类:篮球
public class basketball extends ball {
// 重写父类的playBall方法
public void playBall() {
System.out.println("打篮球吧!兄弟萌");
// 调用父类的方法
super.playBall();
}
public void totalprice() {
int num = 5;
int price=80;
int weight=2;
System.out.println("我买了"+num+"个重"+weight+"kg的"+"球一共花了"+num * price+"元");
}
public static void main(String[] args) {
basketball ball = new basketball();
// 使用父类属性和方法
ball.num = 2;
ball.setNum(10);
ball.setPrice(20);
ball.setWeight(5);
System.out.println(ball.toString());
// 调用重写方法
ball.playBall();
ball.totalprice();
// System.out.println("我买了" + ball.num + "个篮球" + " 一个花了" + ball.totalprice() + "元");
}
}