Jakov
Jakov

Reputation: 1009

Polymorphism: method is changed, but argument value not

I ran following code:

public class Cycling {
    
    public static void main(String[] args) {
        
        Cycle unicycle      = new Unicycle();
        System.out.println("Unicycle name: " + unicycle.name);
        unicycle.ride();
    }
}

class Cycle {
    public String name = "cycle";
    public void ride() {
        System.out.println("Ride cycle!");
    }
}

class Unicycle extends Cycle{
    public String name = "unicycle";
    public void ride() {
        System.out.println("Ride unicycle!");
    }
}

I expected this output:

Unicycle name: unicycle

Ride unicycle!

I got this output:

Unicycle name: cycle

Ride unicycle!

Method was successfully changed, but value of the argument was not. Can someone explain me why?

Upvotes: 2

Views: 41

Answers (3)

Harshal Parekh
Harshal Parekh

Reputation: 6027

Your method is polymorphic, your field is not - because fields are not polymorphic.

You currently have 2 fields with the same name, one field is shadowing another. When you do:

Cycle unicycle = new Unicycle();

Cycle has no idea about the name in the Unicycle class. So when you do unicycle.name, it refers to the one in Cycle class.


Advise: always keep your fields private.


An IDE like IntelliJ Idea would have highlighted this error.

Upvotes: 2

Deepak
Deepak

Reputation: 123

This is classic case of compile-time vs runtime polymorphism.

Compiler resolves the variables during compile time but methods are resolved by JVM during run time.

Upvotes: 2

André Frings
André Frings

Reputation: 129

Thats because when you define a variable of the same name in the subclass, it will have both properties that only share their name. This is called hiding. If you want to access the value of the superclass variable "name", you can call it by super.name.

As you can see, that the variables are handled completely on their own, they can also have a completely different type.

Upvotes: 1

Related Questions