Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance Constraints

I am trying to port some code I wrote in C# to Java, but do not know all of the Java syntax yet. I also have no idea what this type of thing is called, so it is harder to search..I am calling it "inheritance constraints."

Basically, is there a java equivalent to this C# code:

public abstract class MyObj<T> where T : MyObj<T>, new()
{

}

Thanks.


Edit:

Is there any way to do this:

public abstract class MyObj<T extends MyObj<T>> {
    public abstract String GetName();

    public virtual void Test() {
          T t = new T();                // Somehow instantiate T to call GetName()?
          String name = t.GetName();
    }
}
like image 559
Eric Avatar asked Nov 17 '25 14:11

Eric


1 Answers

Not quite. There's this:

public abstract class MyObj<T extends MyObj<T>>

but there's no equivalent to the new() constraint.

EDIT: To create an instance of T, you'll need the appropriate Class<T> - otherwise type erasure will byte you.

Typically you'd add this as a constructor parameter:

public MyObj(Class<T> clazz) {
    // This can throw all kinds of things, which you need to catch here or
    // propagate.
    T t = clazz.newInstance(); 
}
like image 146
Jon Skeet Avatar answered Nov 19 '25 04:11

Jon Skeet