1

I already asked this and it was a messed up description so:

I have a class

private Class MyClass<T extends SomeClass> //where  SomeClass is an abstract class
{
    SomeClass T=new SomeClass(); //Something like that but which works
}

I want to somehow instantiate T or call a method of it perhaps using casting since SomeClass is abstract and the above is invalid

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    You can't instantiate an abstract class. If you are trying to instantiate a concrete implementation, then you need to figure out which concrete implementation you are trying to instantiate. – Nathan Merrill Feb 04 '14 at 13:50
  • they had public class Abc and I have a similar but – user3270982 Feb 04 '14 at 13:51
  • I am trying to make this generic. All I need is to access a method that is implemented in the abstract class. Thats all I want – user3270982 Feb 04 '14 at 13:52

3 Answers3

0

First of all, correct class definition is

public class MyClass<T extends SomeClass> { }

or

private class MyClass<T extends SomeClass> { } 

if this class is an inner class. T will be replaced with some type. It means that

SomeClass T =new SomeClass(); // this T is not the T from class definition

In the line above you are trying to create an instance of abstract class - it's impossible !

Create class which extends SomeClass and implements abstract methods if any and then you can create an instance SomeClass sc = new MyNewClassWhichExtendsSomeClass()

ikos23
  • 4,879
  • 10
  • 41
  • 60
0

The java tutorials has a pretty good solution to this

/**
 * Generic version of the Box class.
 * @param <T> the type of the value being boxed
 */
public class Box<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Just make a method that sets an instance

private class MyClass<T extends SomeClass> { 
     private T t;
     public void set(T t) { this.t = t; }
     //or
     public MyClass(T t){
         this.t = t;
     }
     public void seriousBusiness(){
         SomeClass someClass = (SomeClass) t;
         someClass.someClassMethod();
     }
} 
-1

Edited wrong answer away, new T() doesn't work.

If you want to get access to methods in an abstract class, they have to be static like:

public static int getNumber() {
    return 1;
}

You can then access it by:

SomeClass.getNumber();

Note that SomeClass is not a variable name, but the name of the class!

markusthoemmes
  • 3,080
  • 14
  • 23