Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - extends why the super variable a is 0

Tags:

java

extend

Please look at this code:

class Sup {
    int a = 8;

    public void printA() {
        System.out.println(a);
    }

    Sup() {
        printA();
    }
}

public class Sub extends Sup {
    int a = 9;

    @Override
    public void printA() {
        System.out.println(a);
    }

    Sub() {
        printA();
    }

    public static void main(String[] args) {
        Sub sub = new Sub();
    }
}

result: console print: 0 9
I know that subclass will first calls the superclass constructor
but ,why is the 0 9 , not 8 9?

like image 930
andy.hu Avatar asked Aug 16 '17 13:08

andy.hu


People also ask

Why do we need super () in an extended class?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods. Tip: To understand the "inheritance" concept (parent and child classes) better, read our JavaScript Classes Tutorial.

Why is Super called First in Java?

The base (the superclass) needs to be created first, then you can derive it (the subclass). That's why they called them Parent and Child classes; you can't have a child without a parent. On a technical level, a subclass inherits all the members (fields, methods, nested classes) from its parent.

Why super () is used in Java?

The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

Is super () always called?

Super class constructor is always called during construction process and it's guaranteed that super class construction is finished before subclass constructor is called. This is the case for most if not all the object oriented language.


1 Answers

When the Sup constructor calls printA() it executes the printA method of class Sub (which overrides the method of the same name of class Sup), so it returns the value of the a variable of class Sub, which is still 0, since the instance variables of Sub are not yet initialized (they are only initialized after the Sup constructor is done).

like image 95
Eran Avatar answered Sep 22 '22 14:09

Eran