CoreJava-15 - Fillers - This and Super Keywords

 

Super and This Keywords in Java

 

"This" keywords in Java

Let's say you're designing a class for a person, which has properties such as name, age, and address. Here's an example of how you could use the "this" keyword in the implementation of this class:

public class Person {

    private String name;

    private int age;

    private String address;

 

    public Person(String name, int age, String address) {

        this.name = name;

        this.age = age;

        this.address = address;

    }

 

    public void printDetails() {

        System.out.println("Name: " + this.name);

        System.out.println("Age: " + this.age);

        System.out.println("Address: " + this.address);

    }

}

In this example, the "this" keyword is used to refer to the current instance of the class. For example, in the "printDetails" method, "this.name" refers to the "name" property of the current instance of the Person class. We might also use "this" to disambiguate between a local variable and an instance variable with the same name. For example:

public class Person {

    private String name;

    private int age;

    private String address;

 

    public Person(String name, int age, String address) {

        this.name = name;

        this.age = age;

        this.address = address;

    }

 

    public void setName(String name) {

        this.name = name;

    }

}

In this example, the "setName" method takes a parameter called "name", which has the same name as the "name" property of the Person class. To refer to the instance variable instead of the local variable, we use "this.name" to set the value of the "name" property.

 "Super " keyword in Java

In Java, the "super" keyword is used to refer to the parent class of the current class. It's often used to call the parent class's constructor, methods, or properties.

public class Animal {

    private String name;

 

    public Animal(String name) {

        this.name = name;

    }

 

    public void makeSound() {

        System.out.println("The animal makes a sound.");

    }

}

 

public class Dog extends Animal {

    private String breed;

 

    public Dog(String name, String breed) {

        super(name);

        this.breed = breed;

    }

 

    public void bark() {

        System.out.println("The dog barks!");

    }

 

    @Override

    public void makeSound() {

        System.out.println("The dog barks!");

    }

}

In this example, the "Dog" class is a subclass of the "Animal" class. The "Dog" class has a constructor that takes a "name" and "breed" parameter. When creating a new instance of the "Dog" class, the "super(name)" call is used to call the "Animal" class's constructor and set the "name" property of the animal. The "super" keyword can also be used to call the parent class's methods, as shown in the "makeSound" method in the "Dog" class. By using the "super" keyword, we can call the parent class's "makeSound" method and then add some additional behavior specific to the "Dog" class.

 "This" keyword can be used to refer to the current class instance variables.

Let's say we have a class called "Person" which has three instance variables - name, age, and address. We want to define a constructor that takes three parameters and sets the values of these instance variables. Here's how we can use the "this" keyword to refer to the current class instance variables:

public class Person {

    private String name;

    private int age;

    private String address;

 

    public Person(String name, int age, String address) {

        this.name = name;

        this.age = age;

        this.address = address;

    }

}

In this example, we're using the "this" keyword to refer to the current instance of the "Person" class. When we create a new instance of the "Person" class and pass in values for the "name", "age", and "address" parameters, the constructor sets the values of the corresponding instance variables using the "this" keyword.  For example, we could create a new instance of the "Person" class like this:

Person person = new Person("John", 30, "123 Main Street");

In this case, the "name" instance variable of the "person" object would be set to "John", the "age" instance variable would be set to 30, and the "address" instance variable would be set to "123 Main Street".

 

"This" keyword can be passed as an argument in the method call representing the current object of the class.

Let's say we have a class called "Car" which has two instance variables - make and model. We want to define a method that takes an instance of the "Car" class as a parameter and prints out the make and model of that car. Here's how we can use the "this" keyword to pass the current object of the "Car" class as an argument to the method:

public class Car {

    private String make;

    private String model;

 

    public Car(String make, String model) {

        this.make = make;

        this.model = model;

    }

 

    public void printMakeAndModel() {

        print(this);

    }

 

    private void print(Car car) {

        System.out.println(car.make + " " + car.model);

    }

}

In this example, we're defining a method called "printMakeAndModel" which calls the "print" method and passes the current object of the "Car" class (represented by the "this" keyword) as an argument. The "print" method then takes the "Car" object as a parameter and prints out its make and model. For example, we could create a new instance of the "Car" class like this:

Car car = new Car("Toyota", "Camry");

We could then call the "printMakeAndModel" method on this object:

car.printMakeAndModel();

In this case, the output would be: Toyota Camry

 This” keyword can be used to return the current class instance from any of its methods.

Let's say we have a class called "Person" which has three instance variables - name, age, and address. We want to define a method that returns the current instance of the "Person" class. Here's how we can use the "this" keyword to return the current instance of the class:

public class Person {

    private String name;

    private int age;

    private String address;

 

    public Person(String name, int age, String address) {

        this.name = name;

        this.age = age;

        this.address = address;

    }

 

    public Person getCurrentPerson() {

        return this;

    }

}

In this example, we're defining a method called "getCurrentPerson" which returns the current instance of the "Person" class (represented by the "this" keyword).

For example, we could create a new instance of the "Person" class like this:

Person person = new Person("John", 30, "123 Main Street");

We could then call the "getCurrentPerson" method on this object:

Person currentPerson = person.getCurrentPerson();

In this case, the "currentPerson" variable would contain a reference to the same object as the "person" variable since we're returning the current instance of the class from the "getCurrentPerson" method.

 

"This" keyword can be used to access instance and static variables of the current instance

Let's say we have a class called "BankAccount" which has two instance variables - balance and interestRate, and one static variable - accountNumberCounter. We want to define a method that updates the balance of the current account by adding the interest for the current period. Here's how we can use the "this" keyword to access both the instance and static variables of the current instance:

public class BankAccount {

    private double balance;

    private double interestRate;

    private static int accountNumberCounter = 0;

    private int accountNumber;

 

    public BankAccount(double balance, double interestRate) {

        this.balance = balance;

        this.interestRate = interestRate;

        accountNumberCounter++;

        accountNumber = accountNumberCounter;

    }

 

    public void addInterest() {

        double interest = balance * interestRate;

        this.balance += interest;

    }

 

    public static int getAccountNumberCounter() {

        return accountNumberCounter;

    }

}

In this example, we're defining a method called "addInterest" which calculates the interest for the current period based on the balance and interest rate of the current account (accessed using the "this" keyword) and updates the balance by adding the interest. We're also accessing the static "accountNumberCounter" variable to assign a unique account number to each new instance of the "BankAccount" class. For example, we could create two new instances of the "BankAccount" class like this:

BankAccount account1 = new BankAccount(1000.0, 0.01);

BankAccount account2 = new BankAccount(2000.0, 0.02);

We could then call the "addInterest" method on each object:

account1.addInterest();

account2.addInterest();

In this case, the balances of both accounts would be updated with the interest earned for the current period. We could also call the "getAccountNumberCounter" static method to get the total number of accounts created so far:

int totalAccounts = BankAccount.getAccountNumberCounter();

In this case, the "totalAccounts" variable would contain the value 2, since we've created two instances of the "BankAccount" class. 

"This" keyword can be passed as an argument in the constructor call.

Let's say we have a class called "Person" which has two instance variables - name and age. We want to define a constructor that takes a "Person" object as a parameter and initializes the current instance with the same name and age as the passed object. Here's how we can use the "this" keyword to pass the current instance as an argument in the constructor call:

public class Person {

    private String name;

    private int age;

 

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

 

    public Person(Person otherPerson) {

        this(otherPerson.name, otherPerson.age);

    }

}

In this example, we're defining a constructor called "Person" that takes a "Person" object as a parameter. We're using the "this" keyword to call the first constructor (which takes the name and age as parameters) with the name and age of the passed object. For example, we could create a new instance of the "Person" class like this:

Person person1 = new Person("John", 30);

We could then create a second instance of the "Person" class based on the first instance like this:

Person person2 = new Person(person1);

In this case, the "person2" object would have the same name and age as the "person1" object, since we're passing the "person1" object as an argument to the "Person" constructor using the "this" keyword.

 "This" keyword is used to initiate a constructor of the current class.

Let's say we have a class called "Rectangle" that has two instance variables, width and height. We want to define two constructors - one that takes no parameters and initializes the width and height to 0, and one that takes two parameters to set the width and height. We can use the "this" keyword to call the other constructor from within the current constructor, like this:

public class Rectangle {

    private int width;

    private int height;

 

    public Rectangle() {

        this(0, 0); // calls the two-parameter constructor with values 0 and 0

    }

 

    public Rectangle(int width, int height) {

        this.width = width;

        this.height = height;

    }

}

In this example, we're defining two constructors for the "Rectangle" class. The first constructor takes no parameters and initializes the width and height to 0. It uses the "this" keyword to call the second constructor, passing in the values 0 and 0 as parameters. The second constructor takes two parameters, width, and height, and sets the instance variables to the values of these parameters.

Here's an example of how we could create a new instance of the "Rectangle" class using the first constructor:

Rectangle rect1 = new Rectangle();

In this case, the "rect1" object would have a width and height of 0 since we're calling the constructor with no parameters. We could also create a new instance of the "Rectangle" class using the second constructor:

Rectangle rect2 = new Rectangle(10, 20);

In this case, the "rect2" object would have a width of 10 and a height of 20, since we're passing in these values as parameters. 

"This" keyword can be used to invoke the current class methods.

Let's say we have a class called "Person" that has an instance variable "name" and a method called "introduce" that prints out a message introducing the person with their name. We can use the "this" keyword to invoke the "introduce" method on the current instance of the "Person" class, like this:

public class Person {

    private String name;

 

    public Person(String name) {

        this.name = name;

    }

 

    public void introduce() {

        System.out.println("Hi, my name is " + this.name);

    }

   

    public void greet() {

        this.introduce(); // invokes the introduce() method on the current instance of Person

        System.out.println("Nice to meet you!");

    }

}

In this example, we're defining a class called "Person" with an instance variable "name" and two methods - "introduce" and "greet". The "introduce" method simply prints out a message introducing the person with their name. The "greet" method calls the "introduce" method on the current instance of the "Person" class using the "this" keyword, and then prints out a message saying "Nice to meet you!". Here's an example of how we could create a new instance of the "Person" class and call the "greet" method:

Person john = new Person("John");

john.greet();

In this case, the "john" object would have a name of "John", and the "greet" method would be called on this object. The "greet" method would then call the "introduce" method using the "this" keyword, and output the message "Hi, my name is John". It would then output the message "Nice to meet you!".

comparing the differences between the "this" and "super" keywords in Java: 

This Keyword

Super Keyword

Refers to the current instance of the class

Refers to the parent class of the current class

Can be used to access instance variables of the class

Can be used to access members of the parent class

Can be used to call methods of the current class

Can be used to call methods of the parent class

Can be used to pass the current instance as an argument

Can be used to invoke the constructor of the parent class

Can be used to return the current instance from a method

Comments

Popular posts from this blog

FrontEnd - FAQs - Part 1

Java Script - FAQs

CoreJava - ClassesObjectsMethods - Assignment