[英]Why can I inherit final method from inner class?
I discovered that following code compiles:我发现以下代码编译:
class Ideone
{
public static void main (String[] args){
new Ideone().m();
}
final private void m(){
System.out.println("private final method");
}
class A extends Ideone{
public void method(String [] args){
m();
}
}
}
and executes.并执行。
I am very wondering about this.我很想知道这个。
Can you explain why does java designers(founders) made that it works?你能解释一下为什么java设计者(创始人)让它有效吗?
A final method can be inherited by a sub class regardless the sub class is outside the parent class or inside the parent class.无论子类在父类之外还是在父类内,final 方法都可以被子类继承。 But you cannot override the final method in your subclass.
但是您不能覆盖子类中的 final 方法。 If the final method is private you cannot inherit that in your subclass unless your subclass is inside the parent class (like in your example).
如果最终方法是私有的,则除非您的子类在父类中(例如在您的示例中),否则您无法在子类中继承它。
Since you declare the method private, then final has no effect and is redundant.由于您将方法声明为私有,因此 final 没有效果并且是多余的。
Overriding a private method don't really make much sense.覆盖私有方法并没有多大意义。
It is no different then calling a private method in a class from another method in the same class (which might be public).与从同一类中的另一个方法(可能是公共的)调用类中的私有方法没有什么不同。 That is something that is done often to keep code more readable and method's manageable in size.
这是经常做的事情,以保持代码更具可读性和方法的大小可管理。
I don't think it is a stupid question :)我不认为这是一个愚蠢的问题:)
Take the Builder-pattern for example.以 Builder-pattern 为例。 It utilizes private constructors to make sure the class is constructed the correct way.
它利用私有构造函数来确保以正确的方式构造类。 So understanding what you have available in different scope's, and why is important :)
因此,了解您在不同范围内可用的内容,以及为什么很重要:)
class Ideone {
private String m;
private Ideone(String m) {
System.out.println("Build me with: " + m);
this.m = m;
}
public String getM() {
return m;
}
static class IdeoneBuilder{
String m;
public IdeoneBuilder withM(String m) {
this.m = m;
return this;
}
public Ideone build() {
return new Ideone(this.m);
}
}
public static void main (String[] args){
// new Ideone(); // will not compile
Ideone ideone = new IdeoneBuilder()
.withM("test").build();
}
}
Edit: You can make the class Ideone final, and it will still work.编辑:您可以将 Ideone 类设为 final,它仍然可以工作。 And you are also making it impossible to subclass it.
而且您也无法对其进行子类化。 In other words, you make sure there is no other way to construct an object of your class other than using the builder (unless the use of reflection).
换句话说,您要确保除了使用构建器(除非使用反射)之外,没有其他方法可以构造您的类的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.