Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - using the 'super' keyword

Simple question. I made a class called Tester1 which extends another called Tester2. Tester2 contains a public string called 'ABC'.

Here is Tester1:

public class Tester1 extends Tester2
{
    public Tester1()
    {
         ABC = "Hello";
    }
}

If I instead change line 5 to

super.ABC = "Hello"; 

am I still doing the exact same thing?

like image 402
WildBamaBoy Avatar asked Jul 29 '11 23:07

WildBamaBoy


People also ask

What are the 3 uses of super keyword?

Uses of super keywordTo call methods of the superclass that is overridden in the subclass. To access attributes (fields) of the superclass if both superclass and subclass have attributes with the same name. To explicitly call superclass no-arg (default) or parameterized constructor from the subclass constructor.

Can we use this () and super () in a method?

No, we cannot use this() and super() in a method in java. can a constructor call another constructor java?


2 Answers

Yes. There's only one ABC variable within your object. But please don't make fields public in the first place. Fields should pretty much always be private.

If you declared a variable ABC within Tester1 as well, then there'd be a difference - the field in Tester1 would hide the field in Tester2, but using super you'd still be referring to the field within Tester2. But don't do that, either - hiding variables is a really quick way to make code unmaintainable.

Sample code:

// Please don't write code like this. It's horrible.
class Super {
   public int x;
}

class Sub extends Super {
    public int x;

    public Sub() {
        x = 10;
        super.x = 5;
    }

}

public class Test {
    public static void main(String[] args) {
        Sub sub = new Sub();
        Super sup = sub;
        System.out.println(sub.x); // Prints 10
        System.out.println(sup.x); // Prints 5
    }
}
like image 127
Jon Skeet Avatar answered Sep 24 '22 17:09

Jon Skeet


Yes, the super qualifier is unnecessary but works the same. To clarify:

public static class Fruit {

    protected String color;
    protected static int count;
}

public static class Apple extends Fruit {

    public Apple() {
        color = "red";
        super.color = "red"; // Works the same
        count++;
        super.count++; // Works the same
    }
}
like image 35
hoipolloi Avatar answered Sep 25 '22 17:09

hoipolloi