Why can abstract methods only be declared in abstr

2019-03-12 20:32发布

I understand that in abstract classes methods be both abstract, or not. But why can I not create an abstract method in a "normal", non-abstract class?

Thanks in advance for any explanation!

8条回答
The star\"
2楼-- · 2019-03-12 21:29

Lets start by understanding why we need something like a abstract method. The answer is simple. I dont want my extenders to use my methods as it is, I want them to define their own behavior of a particular method. Since I use this method in other methods of my abstract class. I can provide a /**java doc**/ on the abstract class and point them to use a default behavior.

class abstract LoveTheWorld {
    private int myKindness ;
    public int defaultGiveKindness() {
        myKindness -= 5 ;
        return 5 ;
    }
    /**
    you can use the defaultGiveKindness method, and not define your own behavior
    **/
    public abstract int giveKindness() ;
}

This also tells the extender that they can extend only one class (as per java inheritance rules). Now, if you want to twist this story around, you can use interface instead of a abstract class. But it all depends on what constraints do you want your future developer to adhere to, strict or flexible. Strict will keep it tight and ensure reduced mistakes, flexible will keep it loose and free and promote innovation. The question is **what do you need*8.

查看更多
Evening l夕情丶
3楼-- · 2019-03-12 21:35

Simple answer is ,if the class is not abstract(concreate class) you could be able to instantiate that class and call any method in that class .but let's say if you had declared abstract method in that non abstract class-it's impossible to call that particular abstract method.(to prevent that,we can't declared abstract methods in non abstract class )

查看更多
登录 后发表回答