Question

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();
    }
}
Was it helpful?

Solution

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(); 
}

OTHER TIPS

Judging by your comment above, you're looking for the following construct:

An interface with which you will interact with MyObj objects in code... you will be calling the test() method (standard style in Java is camelcase methods, capitalized classes/interfaces)

public interface IMyObj {
    public void test();
}

You will want the abstract superclass... for the example that you've chosen, you don't NEED to specify any genericism, although you absolutely can if the actual implementation is more reliant on type safety... this class should implement the IMyObj interface:

public abstract class MyObj implements IMyObj {

    String name;

    public abstract String getName();

    public void test() {
        name = getName();
    }
}

From here you would write your subclasses to MyObj...

public class MySubObj1 extends MyObj {
    public String getName() { return "MySubObj1"; }
}

public class MySubObj2 extends MyObj {
    public String getName() { return "MySubObj2"; }
}

Then you safely and correctly use the following snippet in another class:

IMyObj obj = new MySubObj1();
obj.test();

The key is that you use interfaces to hide the implementation, and use abstract classes to hold common code that subclasses will utilize in their implementations.

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top