Okay, so recently I realized that I have some misunderstandings with extending and inheritance inside of java.
So far, my understanding states that you cannot do this
MySubClass myClass = (MySubClass) new MyClass();
That makes enough sense to me, but there are a few gabs and work-arounds that I don't know how to succeed in, such as if a person is trying to get a SubClass from a method that returns the SuperClass. For example:
public static MyClass getNewMyClass() {
return new MyClass();
}
And inside of MySubClass
there are specific methods I want to access, such as
public void sayBye() {
System.out.println("Bye.");
}
So what I would think is I need to do is
((MySubClass) myClass).sayBye();
..but of course that throws a ClassCastException
.
Summary/Question
So basically my question will be, how do I get the subclass of a returned class from a method, or is it possible?
Example: MyClass.getNewMyClass()
returns a new MyClass
, but I want to use the method sayBye()
in its subclass, MySubClass
.
More Information
The reason I'm asking this is because I'm trying to create an API for myself that basically will shorten the development of what I am trying to accomplish. In one of my classes, it contains a whole bunch of methods that returns MyClass
. Some method examples could be public MyClass getNewMyClass() {}
, public MyClass findMyClass(String name)() {}
and so on.
But when I get to exending MyClass
for some extra methods, I have about 10 methods from the superclass
that returns MyClass
, and all of that basically will leave me back to the beginning. Is there the possibility of returning Class<? extends MyClass>
instead, or something similar?
Solved
Thank you everyone so much for your help, it is very much appreciated! So I basically decided to go with delegation
. To solve my issue, here were all of my code and classes, that allowed me to access the superclass
, but return the subclass.
Here was my InheritanceTest.java
public class InheritanceTest {
public static void main(String[] args) {
MyClass myClass = MySubClass.doMath();
if (myClass instanceof MySubClass) {
((MySubClass) myClass).sayBye();
}
}
}
And my MyClass.java
public class MyClass {
protected String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static MyClass getNewMyClass() {
return new MyClass("Toshimaru");
}
public void sayHi() {
System.out.println("Hi.");
}
}
And finally, where it all seems to be resolved, MySubClass.java
public class MySubClass extends MyClass {
public MySubClass(String name) {
super(name);
}
public static MySubClass doMath() {
// Got the new instance of MyClass
MyClass myClass = getNewMyClass();
// And turned it into a MySubClass with myClass' properties.
myClass = new MySubClass(myClass.getName());
return (MySubClass) myClass;
}
public void sayBye() {
System.out.println("Bye.");
}
}