java abstract抽象类学习

java抽象类
java abstract class

有时候,我们需要用到抽象类。比如我们想买水果,但是不确定买的是苹果还是香蕉
Sometimes, we want to abstract a class.For example, We want buy some fruits,but we are not sure we buy apple or pear.

我们抽象出一个类叫水果
Now we can abstract a class named Fruit

水果就作为了一个抽象类和一个父亲类
Fruit is a abstract class and it is a father class.

苹果和梨就作为子类
Apples and pears fruit is child class

注意:我们不能获得一个抽象类的对象 new Fruit() 会发生错误。
note: can not get a new abstract class new Fruit() is wrong

abstract father class
 
public abstract class Fruit {
	public String getColor(String color){
		return color;
	}
 
	public String getWeight(String weight){
		return weight;
	}
}

child class

public class Apple extends Fruit {
	public String getColor(String color){
		System.out.println("color is " + color);
		return color;
	}
 
	public String getWeight(String weight){
		System.out.println("weight is " + weight);
		return weight;
	}
 
	public static void main(String[] args){
		Fruit f = new Apple();
		//Fruit f = new Fruit();   can not get a new abstract class  new Fruit() is wrong
		f.getColor("red");
	}
}


This entry was posted in JAVA and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-abstract/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

2 Responses to java abstract抽象类学习

  1. 陈福山 says:

    请问一个问题:抽象类不能实例化:但是可以定义抽象类数组例如上面两个类。
    Fruit是抽象类。可以Fruit[] f= new Fruit[10];这样子是没问题的,但是我有一点不明,为什么Fruit可以存储他的子类??他的子类必然比父类属性多啊,方法也多啊。。这如何存储? 不懂,求教~

    • 月小升 says:

      new Fruit[10] 数组的时候并没有实例化。
      子类的新增加属性,父类无法使用的。父类只能调用自己有的。子类想用自己属性必须Apple A = new Apple();

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*