简体   繁体   English

可以在Java中扩展(继承)非抽象类吗?

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

Does the class need to have the abstract keyword before it? 该类之前是否需要使用abstract关键字? 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. 是的,除非类本身被声明为final,否则所有非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 http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

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

Yes, but if the class is marked as final, it can't be extended. 是的,但是如果该类被标记为final,则无法扩展。

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. 抽象类也可以有未实现的方法,尽管最终会有一个复杂而严格的层次结构。 .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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