简体   繁体   中英

Can a non-abstract class be extended (inherited from) in Java?

Does the class need to have the abstract keyword before it? Or Does it need to have unimplemented (abstract) methods? Can any normal class be extended?

Can any normal class be extended?

Yes :) Unless it has the final modifier.

Yes, all methods which are not final (static is also a bit different form the rest), can be overridden, unless the class itself is declared final. Abstract methods are only used if you do not provide any implementation in the base class.

不,它不需要有单词abstract,单词abstract只是不允许你直接创建该类的实例,如果你使用单词abstract,你只能创建扩展该抽象类的类的实例。

AbstractClass abs = new ChildClass();

Yes you can extend a class without it needing to be defined as abstract. What this means is that you will be overriding methods. For example, you might make a class

DifferentString extends String

then,

public String toString()
{
    return "Something different";
}

This will mean you can change the original behaviour of the parent class.

Reference:

http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

正如其他人也说过的那样 - 但如果你可以帮助它,最好避免这样做,因为你最终可以更容易地得到所谓的脆弱的基类问题。

Yes, but if the class is marked as final, it can't be extended.

class Foo {
    //some code here
}

class Boo extends Foo {

}

There are some concept confusions here. Unimplemented methods reside in an interface, and you can implement that interface.

You can extend any class as long as its not final.

Edit: What I meant to say that it is preferable to put Unimplemented methods in interfaces as well. Sorry for the poor wording. Abstract classes can have unimplemented methods as well, though you will end up with a complex and rigid hierarchy. .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM