Java – is the constructor not a member of a class?

Constructor is not a member of class? If so, why not inherit?

JLS 7.0 says that constructors are not members, so they cannot inherit Is this true for Java, or is it the general OOP paradigm?

Solution

Constructors are not inherited for good design reasons If they are inherited, you will have problems trying to hide them in the inherited class

Consider this example:

class Plane{
    public Plane(int passengerCapacity,int cargoCapacity){...}
}
class F18 extends Plane{
    public F18(){
        super(0,0);
        ....
    }
}

Now, does the following constructor make sense?

Plane p = new F18(0,0);

It's not true, because subclasses are a special case of parent classes In this particular example, it makes no sense to provide a plane constructor in class F18; The subclass wants to control how the parent class is constructed

If the constructor is inherited and someone wants to hide the parent constructor, they might try the following:

class F18{
    Plane innerPlane;
    public F18(){
        innerPlane = new Plane(0,0);
    }
}

It is not a real solution, because in every method and attribute, you must write back innerplane Somemethod (), which is almost against the purpose of inheritance

This body also applies to other OOP languages (such as c#)

But what if I really want to inherit constructors from many child classes?

Then your architecture is wrong You don't actually need inheritance to solve your problems You can abstract different parts of another base class / interface for example

class Plane{
    IPilot Pilot;
    public Plane(int passengerCapacity,int cargoCapacity,IPilot pilot){...}
}

A constructor is a method of constructing an object Do you really need many subclasses that can be built in the same way (and use the same logic because they are inherited), or a class that can flexibly remove some of its components?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>