Monday, 1 May 2023

What is Super and this keyword in Java? with example.




In Java, The `Super` And `This` Keywords Are Used To Refer To The Parent Class And The Current Class, Respectively. Here's A Brief Explanation Of Each Keyword Along With An Example:


1. `Super`: The `Super` Keyword Is Used To Refer To The Immediate Parent Class Of A Subclass. It Is Often Used To Call The Constructor Or Method Of The Parent Class. For Example, Suppose We Have A Class `Animal` And A Subclass `Dog`. We Can Use The `Super()` Keyword In The `Dog` Constructor To Call The `Animal` Constructor And Initialize The `Name` Field:


```

class Animal {

    String name;

    public Animal(String name) {

        this.name = name;

    }

}


class Dog extends Animal {

    public Dog(String name) {

        super(name);

    }

}

```


In This Example, The `Dog` Constructor Calls The `Animal` Constructor Using The `Super()` Keyword And Passes The `Name` Argument To It.


2. `This`: The `This` Keyword Is Used To Refer To The Current Class Or Object. It Is Often Used To Distinguish Between Instance Variables And Local Variables That Have The Same Name. For Example, Suppose We Have A Class `Person` With An Instance Variable `Name`. We Can Use The `This` Keyword To Refer To The Instance Variable Inside A Method:


```

class Person {

    String name;

    public void setName(String name) {

        this.name = name;

    }

}

```


In this example, the `setName` method uses the `this` keyword to refer to the instance variable `name`.


In summary, the `super` and `this` keywords in Java are used to refer to the parent class and current class, respectively. The `super` keyword is often used to call the constructor or method of the parent class, while the `this` keyword is often used to refer to the current object or distinguish between instance variables and local variables.

No comments:

Post a Comment

What is Java Permutation and Combination Program?

Here's A Java Program That Calculates Permutations And Combinations: ```Java Import Java.Util.Scanner; Public Class Permutationcombinati...