Can Java constructors construct subclass objects?

Is there any way to modify the class constructed in the constructor?

public class A {
  A() {
    //if (condition) return object of type B
    //else return A itself
  }
}
public class B extends A { }

Basically, I want to use the base class constructor as the factory method Is it possible in Java?

Solution

No, if you want to do this, you will have to use the factory method for a The client of your class has the right to expect that if he makes a new a (), he will get a class a object instead of others

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
分享
二维码
< <上一篇
下一篇>>