I am in situation like I have a class which have two different subclasses.

public class SuperClass{
  String st;
  public String getSt(){
     return st;
  }
}

class A extends SuperClass{

}

class B extends SuperClass{

}

Now I have another method that want to access the getSt inherited method from A and B's object. Like I have a code like this in this method:

String s=objectOfA.getSt();
String s1=ObjectOfB.getSt();

I want to make this call generic, so in place of ObjectOfA,ObjectOfB I want to use something else so I can extend a single copy of this method in a class that can call it accordingly

What do you mean generic? Will the getSt be inherited from the subclasses?
What do you mean: "so I can extend a single copy of this method" ?
You don't extends methods. If getSt is only in the SuperClass then both A,B will have access to the same code.
If the getSt method has different implementation in the A, B classes then there is this code you can use, but again I don't know if it is correct, since you need to post more details:

SuperClass obj_1 = new A();
SuperClass obj_2 = new B();

obj_1.getSt(); // this will call the method from A class
obj_2.getSt(); // this will call the method from B class

According to the above you can do this: It is normally used when the SuperClass is abstract or an interface:

public String methodGeneral(SuperClass sc) {
  return sc.getSt();
}

// ------------------------------------------

A obj_1 = new A();
B obj_2 = new B();

String s1 = methodGeneral(obj_1);
String s2 = methodGeneral(obj_2);

// ------------------------------------------
// OR
SuperClass [] array = SuperClass[2];
array[0] = new A();
array[1] = new B();

// in a loop:
String s1 = methodGeneral(array[0]); // A.getSt
String s2 = methodGeneral(array[1]); // B.getSt

The methodGeneral takes as argument a SuperClass, but if you pass as argument an instance of the A or B class inside the methodGeneral the getSt method of the A or B class will be called.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.