Difference Between "This" And"Super" Keywords in Java

Difference between this andsuper keywords in Java

Lets consider this situation

class Animal {
void eat() {
System.out.println("animal : eat");
}
}

class Dog extends Animal {
void eat() {
System.out.println("dog : eat");
}
void anotherEat() {
super.eat();
}
}

public class Test {
public static void main(String[] args) {
Animal a = new Animal();
a.eat();
Dog d = new Dog();
d.eat();
d.anotherEat();
}
}

The output is going to be

animal : eat
dog : eat
animal : eat

The third line is printing "animal:eat" because we are calling super.eat(). If we called this.eat(), it would have printed as "dog:eat".

What's the difference between this and super keywords in java?

Cool example, overmann :)

Here is another example ... has 2 source files - LevelSub.java which extends LevelSup.java

Save the 2 in some folder, compile using "javac LevelSub.java" (compiler will know from "extends" that it has to compile "LevelSup.java", too), and run "java LevelSub". The comments in the source code should tell you the difference.

this and super are used when there is a name clash for variables or methods (e.g., same name is used in super/sub classes or in a method body, or you want to call a method from the superclass that has been overridden). "this" refers to the current object instance and "super" refers to the one it is inheriting from. For no name clashes, the this or super prefix are redundant.

public class LevelSub extends LevelSup {
protected String myName;

public LevelSub (String myName) {
super ("SuperClass");
this.myName = myName; // sets up instance variable
}

public void print () {
System.out.println ("Hi, this is " + myName); // refers to this.myName
System.out.println ("I am inherited from " + super.myName);
System.out.println ("also known as " + defaultName); // gets from superclass
super.print(); // overridden method of superclass
}

public static void main (String[] args) {
new LevelSub("SubClass").print();
}}

and the other source ...

public class LevelSup {
// cannot be private if accessed by subclass
protected String myName, defaultName = "TopLevel";

public LevelSup (String name) {
myName = name; // this not required, no name clash
}

// cannot be private if accessed by subclass
public void print () {
System.out.println ("Hi, this is " + myName);
}
}

The difference between this and super keywords in java (More advanced information)

It is pretty much explicit this calls the method of on the current object and super calls the method on the current object's parent (Note during the call the method is searched in recursive fashion till it is found.).


from the comments, in your case as you did not implement full() method on the subclass this.full() and full() and super.full() are identical.

Also as this.full() and full() are always same dont use this.full() pattern to minimize the confusion.

Difference between 'super' and 'this'

In Java the keyword this refers to the current object of a class, like in:

class Point {
public int x = 0;
public int y = 0;

public Point(int x, int y) {
this.x = x;
this.y = y;
}

public String toString() {
return x + "," + y;
}
}

class Point3D extends Point {
public int z = 0;

public Point(int x, int y, int z) {
super(x,y);
this.z = z;
}

public String toString() {
return super.toString() + "," + z;
}
}

In the constructor of the class Point this.x refers to the x defined in the class, where x is the parameter passed into the constructor. Here this is used to resolve the ambiguity of the name x. The same thing is true for y.

In the class Point3D the method toString() uses the return value of the super class Point to produce its own return value.

Difference between super keyword vs class name to call method from super class

Calling a method using class name directly means that you want to call a static method, which is not related to any object of the class but the class it self.
That is why the compiler tells you that the method must be static.

As for your question, when you create an object of a child class (Bike class in this example) an object of its parent is always created, on the base of which the particular child object is created.

Its like, when ever you create a Bike, a backing Vehicle is always created, based on which the Bike is created. Otherwise the Bike wouldn't be a Vehicle.

So calling a method by super means, you're telling the compiler to call this method on the class which was used as base(parent) for making this Bike class, from which I'm calling this method.

when you're calling the method by class name, you're telling the compiler to call this method of Vehicle class which is not related to any Vehicle object/instance (and obviously not related to any child (e.g. Bike object or instance as well)

Using this/super in the subclass both give superclass's fields but only super is allowed in subclass constructor

this, the keyword, has two separate jobs.

It's exactly like how + means two completely different things in java: 5 + 2 does integer addition, "foo" + "bar" does string concatenation. Same symbol, 2 unrelated jobs. In english, The word bank means both the land next to a river and also a financial institution. Same word, 2 unrelated jobs.

this is no different.

  1. It means 'this object'. There is only one object here: An object of type Dog. There isn't 'a Dog object' and contained inside it a separate 'Animal super object'. That's not how it works. There is just the Dog object, which contains all fields - any fields you defined in Dog, and any field you defined in Animal.

Hence, this.someFieldDefinedInYourSuperClass = foo; is fine, and that makes sense.


  1. It also means: Select a constructor. This version of the this keyword always comes with parentheses immediately following the keyword. this(params); is what it looks like, and it lets you invoke one of your constructors from another one of your constructors. super() is a similar construct that lets you call one of your super constructors. Note that all constructors must neccessarily use one of these; if you fail to do so the compiler injects super(); as first line in your constructor silently.

Example:

public Student(LocalDate birthDate, String name) {
this(generateNewStudentId(), birthDate, name);
}

public Student(String id, LocalDate birthDate, String name) {
this.id = id;
this.birthDate = birthDate;
this.name = name;
}

here the first usage is simply: Call the other constructor using the provided values. The second (and third and fourth) usages are the 'it is this object' variant.

In your example, you use super(name, age);. This invokes the public Animal(String name, int age) constructor from your superclass. It doesn't "set the name and the age" - it calls that constructor. What that constructor does? Who knows - you'd have to check the source. Maybe the constructor plays Feliz Navidad from the speakers first. You happen to know that it 'just' does this.name = name; this.age = age; but that's just because that's what's currently in Animal.java.

In contrast, this.name = name; means "set the value of this object's name field to the value of the name parameter".

Why can't this() and super() both be used together in a constructor?

this(...) will call another constructor in the same class whereas super() will call a super constructor. If there is no super() in a constructor the compiler will add one implicitly.

Thus if both were allowed you could end up calling the super constructor twice.

Example (don't look for a sense in the parameters):

class A {
public A() {
this( false );
}

public A(boolean someFlag) {
}
}

class B extends A {
public B() {
super();
}

public B( boolean someFlag ) {
super( someFlag );
}

public B ( int someNumber ) {
this(); //
}
}

Now, if you call new B(5) the following constructors are invoked:

     this( false);
A() ---------------> A(false)
^
|
| super();
|
| this();
B() <--------------- B(5) <--- you start here

Update:

If you were able to use this() and super() you could end up with something like this:

(Attention: this is meant to show what could go wrong, if you were allowed to do that - which you fortunately aren't)

     this( false);
A() ---------------> A(false)
^ ^
| |
| super(); | super( true ); <--- Problem: should the parameter be true or false?
| |
| this(); |
B() <--------------- B(5) <--- you start here

As you can see, you'd run into a problem where the A(boolean) constructor could be invoked with different parameters and you'd now have to somehow decide which should be used. Additionally the other constructors (A() and B()) could contain code that now might not get called correctly (i.e. out of order etc.) since the call to super( true ) would circumvent them while this() wouldn't.

What's the different between super and super() in java?

Both are used in a subclass as a way to invoke or refer to its superclass.

super() is a method call you make inside a constructor or inside an overridden method to invoke the superclass's constructor or the superclass's overridden method. The super() call can also take arguments in these cases.

Note that since all classes by default at least inherit from Object, you can always call super() inside a constructor (it must be the first statement in the constructor though). This super() call is in fact ordinarily inserted by the compiler into your no-arg constructor by default.

This can get tricky however if the superclass doesn't have a no-arg constructor though, in which case your call to super() will fail without the appropriate args. A no-arg constructor is ordinarily generated by default however so you don't have to worry about it, but it won't be automatically generated if you've explicitly define another constructor with args, so that's when you may need to explicitly define one yourself.

super without the parens on the other hand is simply a reference to the superclass itself, like any other variable. It can be used to invoke any accessible method in that class or to refer to any of the class's accessible fields, just like you would with any other reference. Eg: super.doSomething() or super.x

Difference between super and ((parent)this)?

Calling ((Parent) this).show(); on what is really a Child object causes Child.show() to be called. Whether you are doing it as myObject.show() or through this makes no difference for which version of the method gets called — it’s always the method determined by the object’s runtime type, in this case Child.

So you have a recursive call, leading to infinite recursion.

super.show() on the other hand calls the method in the super class, in this case Parent.



Related Topics



Leave a reply



Submit