public class SuperClass
{
public void method1()
{
System.out.println(\"superclass method1\");
this.method2();
}
public void method2(
this
always refers to currently executing object.
To further illustrate the point here is a simple sketch:
+----------------+
| Subclass |
|----------------|
| @method1() |
| @method2() |
| |
| +------------+ |
| | Superclass | |
| |------------| |
| | method1() | |
| | method2() | |
| +------------+ |
+----------------+
If you have an instance of the outer box, a Subclass
object, wherever you happen to venture inside the box, even into the Superclass
'area', it is still the instance of the outer box.
What's more, in this program there is only one object that gets created out of the three classes, so this
can only ever refer to one thing and it is:
as shown in the Netbeans 'Heap Walker'.
If you don't want superClass.method1 to call subClass.method2, make method2 private so it cannot be overridden.
Here's a suggestion:
public class SuperClass {
public void method1() {
System.out.println("superclass method1");
this.internalMethod2();
}
public void method2() {
// this method can be overridden.
// It can still be invoked by a childclass using super
internalMethod2();
}
private void internalMethod2() {
// this one cannot. Call this one if you want to be sure to use
// this implementation.
System.out.println("superclass method2");
}
}
public class SubClass extends SuperClass {
@Override
public void method1() {
System.out.println("subclass method1");
super.method1();
}
@Override
public void method2() {
System.out.println("subclass method2");
}
}
If it didn't work this way, polymorphism would be impossible (or at least not even half as useful).
I don't believe you can do it directly. One workaround would be to have a private internal implementation of method2 in the superclass, and call that. For example:
public class SuperClass
{
public void method1()
{
System.out.println("superclass method1");
this.internalMethod2();
}
public void method2()
{
this.internalMethod2();
}
private void internalMethod2()
{
System.out.println("superclass method2");
}
}
You're using the this
keyword which actually refers to the "currently running instance of the object you're using", that is, you're invoking this.method2();
on your superclass, that is, it will call the method2() on the object you're using, which is the SubClass.
You can only access overridden methods in the overriding methods (or in other methods of the overriding class).
So: either don't override method2()
or call super.method2()
inside the overridden version.
"this" keyword refers to current class reference. That means, when it is used inside the method, the 'current' class is still SubClass and so, the answer is explained.