为什么构造函数不能在java中继承?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18147768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why constructors can not be inherited in java?
提问by Mayank Tiwari
采纳答案by Lake
In simple words, a constructor cannot be inherited, since in subclasses it has a different name (the name of the subclass).
简单来说,构造函数不能被继承,因为在子类中它有一个不同的名字(子类的名字)。
class A {
A();
}
class B extends A{
B();
}
You can do only:
你只能这样做:
B b = new B(); // and not new A()
Methods, instead, are inherited with "the same name" and can be used.
相反,方法以“同名”继承并且可以使用。
As for the reason: It would not have much sense to inherit a constructor, since constructor of class A means creating an object of type A, and constructor of class B means creating an object of class B.
至于原因:继承构造函数没有多大意义,因为类A的构造函数意味着创建一个类型A的对象,而类B的构造函数意味着创建一个类B的对象。
You can still useconstructors from A inside B's implementation though:
您仍然可以在 B 的实现中使用A 中的构造函数:
class B extends A{
B() { super(); }
}
回答by Suresh Atta
Reason mentioned in docs of Inheritance
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
子类从其超类继承所有成员(字段、方法和嵌套类)。构造函数不是成员,因此子类不会继承它们,但是可以从子类调用超类的构造函数。
You can refer docs of Providing Constructors for Your Classes
您可以参考为您的类提供构造函数的文档
回答by Rahul Tripathi
Constructors are not members of classes and only members are inherited. You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses.
构造函数不是类的成员,只有成员被继承。您不能继承构造函数。也就是说,您不能使用其超类之一的构造函数来创建子类的实例。
回答by Joop Eggen
- A constructor may only be called with
new
. It cannot be called as a method. - The constructor name is identical to the class name.
- 构造函数只能用
new
. 它不能作为方法调用。 - 构造函数名称与类名称相同。
So inheritance is practically not possible as such. However in a construct one might call other constructors.
所以继承实际上是不可能的。然而,在一个构造函数中,可能会调用其他构造函数。
- In the same class using
this(...)
; - Of the extended class using
super(...)
;
- 在同一个类中使用
this(...)
; - 的扩展类使用
super(...)
;
Example
例子
class A {
A() { } // Constructor
A(int a) { } // Constructor
A(boolean c) { } // Constructor
}
class B extends A {
B() {
this(3, 7);
}
B(int a) {
super();
}
B(String b) {
super(7);
}
B(int a, int c) { // Calls super() implicitly
}
}
A a = new B(8):
There unfortunately is no possibility to use A's constructor for a boolean:
不幸的是,不可能将 A 的构造函数用于布尔值:
B b = new B(true): // ERROR
The language designes could have implemented such a thing as:
语言设计者可以实现这样的事情:
Generate for every public constructor in the base class, a constructor with the same signature if such a constructor is not defined already. Call super
with the same parameters. Call this()
if there is a default constructor.
如果尚未定义此类构造函数,则为基类中的每个公共构造函数生成具有相同签名的构造函数。super
使用相同的参数调用。this()
如果有默认构造函数,则调用。
That seems a bit bloating the code. And is not simply a pointer in a virtual method table, by which method inheritance/overriding works.
这似乎有点使代码膨胀。并且不仅仅是虚拟方法表中的指针,方法继承/覆盖通过它起作用。
回答by Mikhail
What you are talking about is Java language level. If constructors were inherited, that would make impossible to make class private. As we know method visibility can't be downgraded. Object
class has a no argument constructor and every class extends Object
, so in case of constructor inheritance every class would have a no argument constructor. That breaks OO principles.
你说的是Java语言级别。如果构造函数是继承的,那将无法将类设为私有。众所周知,方法可见性不能降级。Object
class 有一个无参数构造函数并且每个类都 extends Object
,因此在构造函数继承的情况下,每个类都会有一个无参数构造函数。这打破了面向对象的原则。
Things are different on bytecode level. When object is created, two operators are called:
字节码级别的情况有所不同。创建对象时,会调用两个运算符:
- new- allocates memory for object
- invokespecial- calls constructor on newly allocated piece of memory
- new- 为对象分配内存
- invokespecial- 在新分配的内存块上调用构造函数
We can modify bytecode so that memory is allocated for Child class and constructor is called from Parent class. In this case we can say that constructors are inherited. One notice if we don't turn off byte code verification, JVM will throw an exception while loading class. We can do this by adding -noverify
argument.
我们可以修改字节码,以便为子类分配内存并从父类调用构造函数。在这种情况下,我们可以说构造函数是继承的。注意,如果不关闭字节码验证,JVM 在加载类时会抛出异常。我们可以通过添加-noverify
参数来做到这一点。
Conclusion:
结论:
- Constructors are not inherited on language level due to OO principles
- Constructors are inherited on bytecode level
- 由于面向对象原则,构造函数不会在语言级别继承
- 构造函数在字节码级别继承
回答by Nikhil
Simple answer I observed, You cannot invoke or use constructors of parent class in child class directly but methods of parent class you can use directly in child class.
我观察到的简单答案是,您不能直接在子类中调用或使用父类的构造函数,但可以直接在子类中使用父类的方法。
In case you have method in child class with same name as in parent class at that time only you need to use "super" keyword to invoke parent class method resolve call ambiguity.
如果您当时在子类中有与父类同名的方法,则只需使用“super”关键字来调用父类方法即可解决调用歧义。
"To invoke" parent class constructor in child class you always need "super" keyword. So parent class constructors are "not directly available" like parent class methods in child class so we can say constructors can not be inherited.
“要在子类中调用”父类构造函数,您总是需要“super”关键字。所以父类的构造函数像子类中的父类方法一样“不直接可用”,所以我们可以说构造函数不能被继承。
回答by Ashwini E
No, constructors will not be inherited to subclass, eventhough its a non-static member it will not be inherited to subclass because constructors will not be loaded inside the object, it is used to create the object. Constructors are like a non-static initializer
不,构造函数不会被继承到子类,即使它是一个非静态成员,它也不会被继承到子类,因为构造函数不会被加载到对象内部,它用于创建对象。构造函数就像一个非静态初始化器
回答by user6521421
Only fields, methods, and nested classes are the membe of any class not Constructors. A subclass inherits all the members like (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
只有字段、方法和嵌套类是任何类的成员,而不是构造函数。子类从其超类继承所有成员,如(字段、方法和嵌套类)。构造函数不是成员,因此子类不会继承它们,但是可以从子类调用超类的构造函数。
回答by KGhatak
Syntactic limitations can often be circumvented should there be any reason for a feature in a conceptual way. With this, I believe, the real reason for not supporting inheritance of constructor is not due to syntactic limitations but rather due to semantics.
如果某个功能在概念上有任何理由,通常可以规避语法限制。有了这个,我相信,不支持构造函数继承的真正原因不是由于语法限制,而是由于语义。
Conceptually inheritance provides a mechanism to acquire (or inherit) a behavior and most likely without writing any piece of code since its purpose is to provide code-reuse. For a child class, it makes no case to inherit the behavior of initialization of its parent class. After all, an inherited behavior finds its best use when an external caller can use it without knowing who (in the parent chain) actually has implemented it. As you can see, a caller hardly has any business knowing how a parent class is initialized via its child class, there is no discernible reason for supporting inheritance for a (parent class's) constructor.
从概念上讲,继承提供了一种获取(或继承)行为的机制,并且很可能无需编写任何代码,因为其目的是提供代码重用。对于子类,没有必要继承其父类的初始化行为。毕竟,当外部调用者可以在不知道谁(在父链中)实际实现它的情况下使用它时,继承的行为找到了它的最佳用途。如您所见,调用者几乎不需要知道父类是如何通过其子类初始化的,没有明显的理由支持(父类的)构造函数的继承。
回答by J.d. Patel
you can't inherited constructors but you can inherit initialized value in constructor like
您不能继承构造函数,但可以继承构造函数中的初始化值,例如
class test1 {
int a,b;
test1(){
a = 100;
b = 20;
}
}
class test2 extends test1 {
test2(){
// do something
}
}
class test {
public static void main(String[] args) {
test2 t = new test2();
int a = t.a;
int b = t.b;
System.out.println(a+b);
}
}