为什么不能使用私有抽象方法?
假设我有我的经典作品:
Let's say I have my classic:
public abstract class Mammal {
private int numLegs;
private String voice;
private Coat coat;
public abstract void eat();
public abstract void speak();
public abstract void sleep();
private abstract void ingestFood(Food f); //The abstract method ingestFood in type Mammal can only set a visibility modifier, one of public or protected
}
通过以下具体实现:
public class Dog extends Mammal {
private int numLegs = 4;
private String voice = "Woof!";
private Coat coat = new Coat(COATTYPE.FUR, COATCOLOR.BROWN);
@Override
public void eat()
{
Rabbit r = chaseRabbits();
if (r != null) ingest(r);
else {
Garbage g = raidBin();
if (g!= null) ingest(g);
}
}
@Override
private void ingest(Food f)
{
gobbleItAllUpInFiveSeconds(f);
stillFeelHungry();
}
}
public class Human extends Mammal {
private int numLegs = 2;
private String voice = "Howdy!!";
private Coat coat = new Coat(COATTYPE.SKIN, COATCOLOR.PINK);
@Override
public void eat()
{
Food f = gotoSuperMarket();
ingest(f);
}
@Override
private void ingest(Food f)
{
burp();
}
}
现在,我想在哺乳动物
类,哺乳动物的所有实例均可调用,例如
Now, I want a method in the Mammal
class that is callable by all instances of the mammal, e.g.
public String describe() {
return "This mammal has " + this.numLegs + "legs, a " + this.coat.getColor() + " " this.coat.getCoatType() + " and says " + this.voice;
}
我的问题是,通过制作 Mammal
类不是抽象的,是否有可能单独创建哺乳动物?例如,
My question is that, by making the Mammal
class not abstract, is it possible to create a mammal by itself? E.g.
Mammal me = new Mammal();
您不应该这样做。
但是,我确实希望有一些由父类实现的公共方法,所有子类都调用这些方法,但是每个子类都调用自己的私有方法。
However, I do want to have some public methods that are implemented by the parent class that all subclasses call, but that each call their own private method.
您完全可以在抽象类中实现方法:
You can totally have implemented methods in an abstract class:
抽象类类似于接口。您无法实例化它们,并且它们可能包含使用或不使用实现声明的方法的混合。
"Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation."
https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html