Perhaps, but not the way you have it.
You need to add the no-args constructor to the base class and what it is!
public abstract class A { private String name; public A(){ this.name = getName(); } public abstract String getName(); public String toString(){ return "simple class name: " + this.getClass().getSimpleName() + " name:\"" + this.name + "\""; } } class B extends A { public String getName(){ return "my name is B"; } public static void main( String [] args ) { System.out.println( new C() ); } } class C extends A { public String getName() { return "Zee"; } }
If you do not add the constructor (any) to the class, the compiler adds the default constructor no arg for you.
When defualt no arg calls super (); and since you donβt have it in the superclass, you will get this error message.
As for the question, this is itself.
Now, expanding the answer:
Do you know that creating a subclass (behavior) to indicate a different value (data) does not make sense? !!! I hope you do it.
If the only change is the "name", then just one parameterized class is enough!
Therefore, you do not need this:
MyClass a = new A("A"); MyClass b = new B("B"); MyClass c = new C("C"); MyClass d = new D("D");
or
MyClass a = new A(); // internally setting "A" "B", "C" etc. MyClass b = new B(); MyClass c = new C(); MyClass d = new D();
When you can write this:
MyClass a = new MyClass("A"); MyClass b = new MyClass("B"); MyClass c = new MyClass("C"); MyClass d = new MyClass("D");
If I had to change the signature of the BaseClass constructor method, I would have to change all subclasses.
Itβs good that inheritance is an artifact that creates HIGH cohesion, which is undesirable in OO systems. It should be avoided and possibly replaced with a composition.
Think about whether they are really needed as a subclass. This is why you often come across interfaces that were used by insted:
public interface NameAware { public String getName(); } class A implements NameAware ... class B implements NameAware ... class C ... etc.
Here, B and C could inherit from A, which would create a very high connection between them using interfaces, the connection will decrease, if A decides that there will no longer be "NameAware", the rest of the classes will not be violated.
Of course, if you want to reuse the behavior, this will not work.