Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading of methods when extending classes in Java

If I have this code:

interface Tre{
    public void f();
}
public class TreA implements Tre{
    int x = 1;
    public void f(){
        x++; 
        System.out.println("Y"+x);
    }
    public static void main(String[] a){
        Tre a3 = new TreB(); a3.f();
    }
}
class TreB extends TreA{
    public void f(){
        x--;         
        super.f();
        System.out.println("X"+x);}
}

I do not understand why the output is Y1 X1. If I extend the class TreA, I'll overwrite its f() method and get a copy of int x=1. Calling super.f() should call f() belonging to the class TreA but what about x? I have never instantiated TreA. Why does it use the x belonging to TreB ? What about the scope in this case?

like image 711
bog Avatar asked May 21 '26 04:05

bog


1 Answers

Extending a class means that your child class include everything from the parent class.

I'll overwrite it's f() method and get a copy of int x=1

You don't get a copy, you simply have it (you inherited it) and can use it.

Doesn't matter where you use x, it is always the same variable inherited from TreA, so when TreA.f() modify it, it is modifying the only instance of x you have.

I have never instantiated TreA

Creating a child class means you are also creating the parent class. Its constructor gets automatically called when you create the child class.

You have to think like that TreB inherently contains TreA and then you can add things to it and make overrides.

To better visualize the situation, this is your class A:

parent class

and this is its child class B:

child class

as you can see the x variable in B is the variable from class A, not a copy.

like image 127
Loris Securo Avatar answered May 22 '26 16:05

Loris Securo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!