Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - attribute inheritance example

I am puzzled by this inheritance example found in a quizz from a Coursera Java course:

  • class B is a subclass of class A
  • class B getPrefix() method overrides class' A method
  • class B number attribute overrides class' A attribute
class ClassA {
    protected int number;

    public ClassA() {
        number = 20;
    }

    public void print() {
        System.out.println(getPrefix() + ": " + number);
    }

    protected String getPrefix() {
        return "A";
    }
}

class ClassB extends ClassA {
    protected int number = 10;

    protected String getPrefix() {
        return "B";
    }
}



public class Quizz {

    public static void main(String[] args) {

        ClassB b = new ClassB();
        b.print();

        ClassA ab = new ClassB();
        ab.print();

    }
}

When we run this program, the printed result is:

B: 20
B: 20

However, I was expecting this result instead:

B: 10
B: 10

Can you explain how come class A number attribute is printed, and not class B?

like image 940
Tanguy Avatar asked Nov 22 '25 15:11

Tanguy


1 Answers

Can you explain how come class A number attribute is printed, and not class B?

ClassB does not inherit ClassA.number field, but rather hides it.


See:

  • The Java™ Tutorials - Hiding Fields

Within a class, a field that has the same name as a field in the superclass hides the superclass's field.

like image 122
Eng.Fouad Avatar answered Nov 25 '25 04:11

Eng.Fouad