[B]I want to override a method of superclass in subclass the method have same name in both the class. But I want to call the method of superclass with the object of subclass Please Hlep[/B]

Please consider the following code

class a
{
   void a1()
   {
       System.out.println("Hello from a");
   }
  int k = 200;
}
class b extends a
{
    void a1()
    {
            System.out.println("Hello from b");
    }
    int k = 100;
}
public class demoRI
{
    public static void main(String[]args)
    {

    b obj = new a();
    obj.a1();
    System.out.println(obj.k);
     }
}

I had done this code but the object is calling the method of the subclass. I want to call the method of the superclass with the object of subclass. Is it possible can any one help.

I haven't tried it, but can you try this:

b obj = new a();

((a)obj).a1();

With this: (a)obj you are casting the obj to the a class. Then calling the a1 method.
You can try it, but I don't know if it will work.

I have no solution for this thread, but I have a comment on above coding.
class b extends a. The following line of code leads to a compiling error.

b obj = new a();// The instance of a super class cann't always be the one of its sub class.

The following line of code is valid:

a obj = new b(); // the instance of a sub-class will always be the one of its super class

Class Student extends class Person.
The student David, an instance of class Student( the sub class of class Person) is always a person (an instance of its super class) although a person (an instance of super class) is not necessarily a student ( an instance of sub class).
David is a student. Is David a person? Yes, he definitely is a person.
Robert is a person. But he isn't necessarily a student.

Respected Sir's this code had not helped me, please help me..

create a new method in the subclass to pass the call on to the superclass, yhe call that instead

public void superA1() {
super.a1();
}

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.