对于抽象类的总结

1.抽象类中的抽象函数必须在子类中进行override。如Furit中的cost函数必须要在Apple中进行重写

2.子类在进行创建对象时默认会调用父类的构造函数,如果父类中存在有参数的构造函数时,在子类进行中必须显示的实现父类的构造函数,但是如果父类中不存在含有参数的构造函数则子类中不必去显示的实现,但是会默认调用无惨的构造函数。

3.父类中的成员变量如果是用private修饰的,则在子类中是无法使用的,如果是public或者protected则可以使用。

4.父类也可以声明对象,但是父类必须使用子类来强制转换

抽象类实例:

1)建立一个抽象类叫做”fruit”

public abstract class Fruit {
    
	public String name;
	public String color; // 颜色
	public String flavour; // 味道
	public double weight; // 重量
	public double price; //

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public String getFlavour() {
		return flavour;
	}

	public void setFlavour(String flavour) {
		this.flavour = flavour;
	}

	public double getWeight() {
		return weight;
	}

	public void setWeight(double weight) {
		this.weight = weight;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}
    
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
    
	public Fruit(String name) {
		this.name = name;
		System.out.println("我是父类构造函数    "+name);
	}
	public abstract void cost();
	
	public void describe() {
		System.out.println("I am an"+name+"color is"+color+"and taste is"+flavour);
	}
}
2) 建立一个子类叫做”Apple”继承Fruit

public class Apple extends Fruit {
    
	private String demo;
	
	public Apple() {   //构造函数
		super("苹果");
		System.out.println("开始初始化  apple");
		color = "红色";
		demo = "你好吗?";
	}
	
	public String getDemo() {
		return demo;
	}

	public void setDemo(String demo) {
		this.demo = demo;
	}
	
	public void sayDemo() {
		System.out.println(demo);
	}
    
	//抽象方法必须得实现
	public void cost() {   
         System.out.println(getWeight()*getPrice());
	}

}
3)创建一个main测试

public static void main(String[] args) {
		Apple a = new Apple();
		Fruit f = new Apple();   //子类可以转换成为父类
		a.setName("苹果");
		a.setColor("青");
		a.setFlavour("酸");
		a.setPrice(2.5);
		a.setWeight(1.5);
		a.describe();
		a.sayDemo();
		a.cost();
		f.describe();
}
最后结果如下:

我是父类构造函数    苹果
开始初始化  apple
我是父类构造函数    苹果
开始初始化  apple
I am an苹果color is青and taste is酸
你好吗?
3.75
I am an苹果color is红色and taste isnull






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值