为什么我不能有一个私有的抽象方法? [英] Why can't I have an private abstract method?

查看:34
本文介绍了为什么我不能有一个私有的抽象方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有我的经典:

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();  
     }
}

现在,我想要 Mammal 类中的一个方法,该方法可由哺乳动物的所有实例调用,例如

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

这篇关于为什么我不能有一个私有的抽象方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆