Query about the reserved word "super ()" JAVA

6

Good afternoon, in my project I have the following attributes and constructor of an Abstract Class:

//Attributes
private int number;

//Constructor
public Card ( int number ) {

    this.number = number ;
}

Of which inherits the following Class:

public abstract class SpainCard extends Card {

//Attributes
private int number ;
private String suit ;

//Constructor
public SpainCard(int number, String suit) {

    super(number);
    this.suit = suit;

}

My query is the following, which generates the reserved word super(number); in the constructor of my Abstract class SpainCard ? Am I inheriting attriburo int number from my class father, or what does JAVA internally when using super(); ?.

It is a query so you can better understand how it works and is used in a good way super(); since my code works like this, but I have doubts exactly what it does.

Thank you very much, I hope you can explain me in more detail.

    
asked by Matias Simone 27.04.2017 в 21:21
source

3 answers

2

I think the Java documentation explains it quite clearly, the problem is that it is in English.

Let me leave it here translated, so that it helps the understanding of future programmers, since it is an interesting question, especially when we start programming in Java.

Use of the keyword super

Access to Superclass members

If your method replaces one of the methods of your superclass, you can invoke the overwritten method (override) by using the keyword super . You can also use super to refer to a hidden field (although hiding fields is discouraged).

Consider this class, Superclase :

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

Here is a subclass, called Subclase , which replaces (overwrites)%% of%:

Here is a subclass, called Subclass, that overrides printMethod ():

public class Subclass extends Superclass {

    // sobreescribe printMethod en Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within the Subclass, the simple name printMethod () refers to the one declared in Subclass, which replaces the one of Superclass. Therefore, to refer to printMethod() inherited from printMethod() , Superclase must use a qualified name, using Subclase as shown. When we compile and execute super print the following:

Printed in Superclass.
Printed in Subclass.

Subclass builders

The following example illustrates how to use the keyword Subclase to invoke the constructor of a superclass. Remember the example super that Bicycle is a subclass of MountainBike . Here is the constructor Bicycle (subclass) that calls the constructor of the superclass and then adds an initialization code of its own:

public MountainBike(int startHeight, 

                        int startCadence,
                        int startSpeed,
                        int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    }   

The invocation of a superclass constructor must be the first line in the subclass constructor.

The syntax for calling a superclass constructor is

super();

o:

super (lista de parámetros);

With MountainBike , the constructor is called without arguments from the superclass. With super() , the superclass constructor is called with a corresponding parameter list.

  

Note: If a constructor does not explicitly invoke a constructor of   superclass, the Java compiler automatically inserts a call to the   constructor without arguments of the superclass. If the superclass does not have   a constructor without an argument, you will get an error in time of   compilation. The object has such a constructor, so if the object is   the only superclass, no problem.

If a subclass constructor invokes a constructor of its superclass, explicitly or implicitly, you can imagine that there will be a complete string of called constructors, all the way back to the Object constructor. In fact, this is the case. It is called constructor chain , and it is necessary to be aware of this when there is a long line of descent of class.

answered by 27.04.2017 / 22:38
source
7

It's easy to try it:

public class SpainCard extends Card {

    //Attributes
    private int number;
    private String suit;

    //Constructor
    public SpainCard(int number, String suit) {

        super(number);
        this.suit = suit;

    }

    public static void main(String[] args) {
        SpainCard c = new SpainCard(1, "");
        System.out.println("number " + c.number);
    }
}

prints 0 . That is, the parent constructor ( Card ) used its own attribute. Which is logical. The number attribute of the child was not assigned.

  

What does JAVA do internally when using super(); ?

Simply call the father's constructor - with those arguments. Now, the constructor of the father, when it was compiled, "knew" that in the statement this.number = number ; the attribute that is on the left is "its" attribute. Nothing changes that when executing this constructor an object of the daughter class is actually being built, with its own attribute with the same name. The concrete attribute (field) that is used is fixed at compile time. There is not something like a "override" of attributes in Java , only of methods.

I hope it is clear to you that this use of the same private attribute in two classes (one that extends to another) is not an error in itself, but it is not advisable.

To clarify more:

public class Card {
    private int number = -1;

    public Card ( int number ) {
         System.out.println("Entrando a constructor de Card: number era " + this.number);
         this.number = number ;
         System.out.println("Saliendo de constructor de Card;  number es " + this.number);
    }
}

public class SpainCard extends Card {

    private int number = -2;
    private String suit;

    public SpainCard(int number, String suit) {
        super(number);
        this.suit = suit;
        System.out.println("Saliendo de constructor de SpainCard; mi number es " + this.number);

    }

    public static void main(String[] args) {
        SpainCard c = new SpainCard(10, "");
        System.out.println("number " + c.number);
    }
}

You should be able to predict (exam question!) what this prints.

  

Entrando a constructor de Card; number era -1 Saliendo de constructor de Card; number es 10 Saliendo de constructor de SpainCard; mi number es -2 number -2

    
answered by 27.04.2017 в 21:35
1

Your code in this passage:

//Constructor
public SpainCard(int number, String suit) {

    super(number);//llamada al constructor de la Clase Padre (Card) ya que hereda de ella y le envia el parametro number , el cual tiene definido el constructor de Card
    this.suit = suit;

}

In Java when creating an instance of the Class the constructor is called, and the constructor in its first line calls the constructor of the parent class with super ();

Let's see some examples

public class Clase1
{
    public Clase1()
    {
        //el compilador añade la llamada a super() ya que esta no fue añadida por el programador en este caso llama a Object
        System.out.println("constructor Clase1");
    }

    public static void main(String []args)
    {
        Clase3 clase3 = new Clase3();
    }

}

class Clase2 extends Clase1
{
    public Clase2()
    {
        //el compilador añade la llamada a super() ya que esta no fue añadida por el programador en este caso llama a Clase1
        System.out.println("constructor Clase2");
    }
}

class Clase3 extends Clase2
{
    public Clase3()
    {
        //el compilador añade la llamada a super() ya que esta no fue añadida por el programador en este caso llama a Clase2
        System.out.println("constructor Clase3");
    }
}
    
answered by 27.04.2017 в 22:03