Showing posts with label Java keyword. Show all posts
Showing posts with label Java keyword. Show all posts

Tuesday, September 19, 2023

super Keyword in Java With Examples

The super keyword in java is essentially a reference variable that can be used to refer to class' immediate parent class.

Usage of super in Java

super keyword in Java can be used for the following-

  • Invoke the constructor of the super class. See example.
  • Accessing the variables and methods of parent class. See example.

First let's see how code will look like if super() is not used.

Let's say there is a super class Shape with instance variables length and breadth. Another class Cuboids extends it and add another variable height to it. When you are not using super(), constructors of these 2 classes will look like-

public class Shape {
 int length;
 int breadth;
 Shape(){
  
 }
 // Constructor
 Shape(int length, int breadth){
  this.length = length;
  this.breadth = breadth;
 }
}

class Cuboids extends Shape{
 int height;
 //Constructor
 Cuboids(int length, int breadth, int height){
  this.length = length;
  this.breadth = breadth;
  this.height = height;
 }
}

It can be noticed there are 2 problems with this approach-

  • Duplication of code as the same initialization code in the constructor is used twice. Once in Cuboids class and once in Shape class.
  • Second and most important problem is super class instance variables can not be marked as private because they have to be accessed in child class, thus violating the OOP principle of Encapsulation.

So super() comes to the rescue and it can be used by a child class to refer to its immediate super class. Let's see how super keyword can be used in Java.

Using super to invoke the constructor of the super class

If you want to initialize the variables that are residing in the immediate parent class then you can call the constructor of the parent class from the constructor of the subclass using super() in Java.

Note: If you are using super to call the constructor of the parent class then super() should be the first statement inside the subclass' constructor. This ensures that if you call any methods on the parent class in your constructor, the parent class has already been set up correctly.

Java example code using super

public class Shape {
 private int length;
 private int breadth;
 Shape(){
  
 }
 Shape(int length, int breadth){
  this.length = length;
  this.breadth = breadth;
 }
}

class Cuboids extends Shape{
 private int height;
 Cuboids(int length, int breadth, int height){
  // Calling super class constructor
  super(length, breadth);
  this.height = height;
 }
}

Here it can be noticed that the instance variables are private now and super() is used to initialize the variables residing in the super class thus avoiding duplication of code and ensuring proper encapsulation.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.

That will happen when a constructor is explicitly defined for a class. Then the Java compiler will not insert the default no-argument constructor into the class. You can see it by making a slight change in the above example.

In the above example, if I comment the default constructor and also comment the super statement then the code will look like-

public class Shape {
  private int length;
  private int breadth;
  /*Shape(){
   
  }*/
  Shape(int length, int breadth){
   this.length = length;
   this.breadth = breadth;
  }
}

class Cuboids extends Shape{
  private int height;
  Cuboids(int length, int breadth, int height){
   // Calling super class constructor
   /*super(length, breadth);*/
   this.height = height;
  }
}

This code will give compile-time error. "Implicit super constructor Shape() is undefined".

Using super to access Super class Members

If method in a child class overrides one of its superclass' methods, method of the super class can be invoked through the use of the keyword super. super can also be used to refer to a hidden field, that is if there is a variable of the same name in the super class and the child class then super can be used to refer to the super class variable.

Java example showing use of super to access field

public class Car {
 int speed = 100;
 
}

class FastCar extends Car{
 int speed = 200;
 FastCar(int a , int b){
  super.speed = 100;
  speed = b;
 }
}

Here, in the constructor of the FastCar class super.speed is used to access the instance variable of the same name in the super class.

Example showing use of super to access parent class method

public class Car {
 void displayMsg(){
  System.out.println("In Parent class Car");
 }
}

class FastCar extends Car{
 void displayMsg(){
  System.out.println("In child class FastCar");
  // calling super class method
  super.displayMsg();
 }
 public static void main(String[] args){
  FastCar fc = new FastCar();
  fc.displayMsg();
 }
}
public class Test {

 public static void main(String[] args){
  FastCar fc = new FastCar();
  fc.displayMsg();
 }
}

Output

In child class FastCar
In Parent class Car

Points to note-

  • super keyword in java is a reference variable to refer to class' immediate parent class.
  • super can be used to invoke the constructor of the immediate parent class, that's help in avoiding duplication of code, also helps in preserving the encapsulation.
  • If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
  • super can also be used to access super class members.
  • If a variable in child class is shadowing a super class variable, super can be used to access super class variable. Same way if a parent class method is overridden by the child class method then the parent class method can be called using super.

That's all for this topic super Keyword in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Keyword in Java With Examples
  2. this Keyword in Java With Examples
  3. static Keyword in Java With Examples
  4. TypeWrapper Classes in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Method Overloading in Java
  2. Constructor Chaining in Java
  3. Inheritance in Java
  4. Covariant Return Type in Java
  5. How to Read Input From Console in Java
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Deadlock in Java Multi-Threading
  8. Java ThreadLocal Class With Examples

Sunday, April 3, 2022

final Keyword in Java With Examples

final keyword in java has its usage in preventing the user from modifying a field, method or class.
  • final field- A variable declared as final prevents the content of that variable being modified.
  • final method- Final method in Java prevents the user from overriding that method.
  • final class- Final class in Java can not be extended thus prevents inheritance.

final variable in Java

A variable can be declared as final in Java which prevents its contents from being modified. A final variable can be initialized only once but it can be done in two ways.

  • Value is assigned when the variable is declared.
  • Value is assigned with in a constructor.

Please note that the final variable that has not been assigned a value while declaring a variable is called blank final variable in Java, in that case it forces the constructor to initialize it.

Java final variable examples

In the following examples you can see that any attempt to modify value of a final field results in compile time error.

final variable value can't be changed

Compilation error if value of a final variable is changed in the setter method.

final variable value can't be changed

Compilation error if value of a final variable is changed using an object.

Final blank variable example

final blank variable in Java

Compilation error that the blank final variable is not initialized. In that case this variable should be initialized in a constructor of the class.

final object in Java

Making an object reference variable final is a little different from a normal variable as in that case object fields can still be changed but the reference can't be changed. That is applicable to collections too, a collection declared as final means only its reference can't be changed values can still be added, deleted or modified in that collection.

Example of final object

final object in Java

Here you can see that the value of field i can be changed but trying to change object reference results in compile time error.

final method parameter

Parameters of a method can also be declared as final in Java to make sure that parameter value is not changed in the method. Since java is pass by value so changing the parameter value won't affect the original value anyway. But making the parameter final ensures that the passed parameter value is not changed in the method and it is just used in the business logic the way it needs to be used.

As example

private static Employee getData(final String empId, final String lastName, final String firstName, final int age){
  ...
  ...
}

Final variables and thread safety

Variables declared as final are essentially read-only thus thread safe.

Also if any field is final it is ensured by the JVM that other threads can't access the partially constructed object, thus making sure that final fields always have correct values when the object is available to other threads.

How final keyword in Java relates with inheritance

The use of final with the method or class in Java relates to the concept of inheritance. You can have a final method or a final class in Java ensuring that a method declared as final can't be overridden and the class declared as final can't be extended.

final method in Java

A method can be declared as final in order to avoid method overriding. Method declared as final in super class cannot be overridden in subclass.

If creator of the class is sure that the functionality provided in a method is complete and should be used as is by the sub classes then the method should be declared as final in Java.

Benefit of final method

Final method in Java may provide performance enhancement. Generally in Java, calls to method are resolved at run time which is known as late binding.

Where as in case of final methods since compiler knows these methods can not be overridden, call to these methods can be resolved at compile time. This is known as early binding. Because of this early binding compiler can inline the methods declared as final thus avoiding the overhead of method call.

Final method example in Java

final method in Java

final Class in Java

A class declared as final can't be extended thus avoiding inheritance altogether.

If creator of the class is sure that the class has all the required functionality and should be used as it is with out extending it then it should be declared as final in Java.

Declaring a class as final implicitly means that all the methods of the class are final too as the class can't be extended.

It is illegal to declare a class as both final and abstract. Since abstract class by design relies on subclass to provide complete implementation.

Java final class example

final class in Java

Benefits of final class in Java

  • Since all the methods in a final class are implicitly final thus final class may provide the same performance optimization benefit as final methods.
  • Restricting extensibility may also be required in some cases essentially when using third party tools.
  • A class can be declared final when creating Immutable Class in Java.

Points to note-

  • final keyword in Java can be used with fields, methods and classes.
  • final variables are essentially read only and it is a common convention to write the final variables in all caps. For example
    Private final int MAXIMUM_VALUE = 10
  • final variables that are not initialized during declaration are called blank final variable in that case it forces the constructor to initialize it. Failure to do so will result in compile time error.
  • final variables can be initialized only once, assigning any value there after will result in compile time error.
  • final variables are read-only thus thread safe.
  • In case of final object, reference can't be changed.
  • final methods can't be overridden
  • final classes can't be extended.
  • final methods are bound during compile time (early binding), which means compiler may inline those methods resulting in performance optimization.

That's all for this topic final Keyword in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Vs finally Vs finalize
  2. Method Overloading in Java
  3. super Keyword in Java With Examples
  4. Type Casting in Java With Conversion Examples
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. How to Create Immutable Class in Java
  2. static Keyword in Java With Examples
  3. Why Class Name And File Name Should be Same in Java
  4. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  5. Difference Between throw And throws in Java
  6. Exception Handling in Java Lambda Expressions
  7. How ArrayList Works Internally in Java
  8. Just In Time Compiler (JIT) in Java

Tuesday, May 11, 2021

this Keyword in Java With Examples

this keyword in java is a reference to the current object, meaning the object whose method or constructor is being called. It can be used inside any method or constructor to refer to the current object.

If the definition of this keyword in Java is sounding confusing, let's clear it with an example-

class ThisDemo{
 int age;
 String name;
 ThisDemo(int a, String b){
  age = a;
  name = b;
 }
 void displayData(){
  System.out.println("Age - " + age + " Name- " +name);
  System.out.println("reference of this " + this);
 }
 
}
public class ThisExample {
 public static void main(String[] args) {
  ThisDemo thisDemo = new ThisDemo(10, "Ram");
  thisDemo.displayData();
  System.out.println("reference of ThisDemo " + thisDemo);
 }
}
 

In the given example, it can be seen that in method displayData() this is printed and in the main method thisDemo object is printed. Reference of object thisDemo and reference of this in method dispalyData() would be same as this is reference to the object on which the method is invoked.

Output

 Age - 10 Name- Ram
reference of this org.netjs.examples.ThisDemo@19e0bfd
reference of ThisDemo org.netjs.examples.ThisDemo@19e0bfd

It can be seen in the output that the same reference is printed for object thisDemo and this.

Note that this can't be explicitly assigned a reference to an object of a class it will result in compilation error.

MyClass myObj = new MyClass();
// This line will give error, as assigning reference of an
// object to this is not permitted
this = myObj;

Usage of this keyword in Java

this in Java used in case of instance variable hiding

Before going into how this keyword can be used in case of instance variable hiding first let's see what actually instance variable hiding is. In Java we can't have two local variables with the same name with in the same scope. So it will be compiler error if we try some thing like-

class A {
 int a;
 double b;
 double b;// Compiler error

 public void displayData(){
  System.out.println("Values - a = " + a + " b= " + b);
 }
}

Here we are trying to have two variables with the same name b with in the same scope (scope of the class) which results in compilation error.

But in different scope it is perfectly legal to have variables with the same name, so we can have the variables with the same name in the method as well as in the class as instance variable. Thus it is perfectly legal to have some thing like

class InstanceHiding {
 int a = 50;
 double b = 60;

 public void displayData(){
  int a = 10;
  double b = 20;
  System.out.println("Values a = " + a + " b = " + b);
 }
 public static void main(String[] args) {
  InstanceHiding instanceHiding = new InstanceHiding();
  instanceHiding.displayData();
 }
} 
 

No error here because the variables are with in the different scope. But the point to note here is that local variable hides the instance variable with in the scope of the local variable. As can be seen from the output of the program.

Values a = 10 b = 20.0

With in the method, method variables get priority over the instance variables and hide them. If we comment the variables with in the method then the output would have been -

Values a = 50 b = 60.0

this can be useful in such cases to avoid name collisions, since we know that this in Java refers to the object on which the method is called so this can be used to access the instance variables.
Conventionally people prefer to have same names for variables in the case of constructors to have clarity, use of this helps there to initialize fields.

An Example
class InstanceHiding {
 int a;
 double b;
 InstanceHiding(int a, double b){
  this.a = a;
  this.b = b;
 }
 public void displayData(){  
  System.out.println("Values a = " + a + " b = " + b);
 }
 public static void main(String[] args) {
  InstanceHiding instanceHiding = new InstanceHiding(10, 20);
  instanceHiding.displayData();
 }
}

Here we are referring the instance variables using the this keyword like this.a and initializing them in the constructor.

this keyword used in case of overloaded constructors

In Java this keyword can be used to invoke overloaded constructors in a class. There are 2 restrictions that should be kept in mind while doing that.

  • this() must be the first statement with in the constructor.
  • instance variable of the constructor's class can not be used in a call to this().
class ConstrOverLoading {
 int a;
 double b;
 ConstrOverLoading(int a, double b){
  this.a = a;
  this.b = b;
 }
 ConstrOverLoading(int a){
  this(a, 0.0);
 }
 ConstrOverLoading(){
  this(0);
 }
}

It can be noticed here that only one of the constructor ConstrOverLoading(int a, double b) is doing any assignment other constructors are merely invoking that constructor through this(). This use of this helps in reducing the duplication of code.

Note that while using with in a constructor either this() or super() can be used not both as both have the restriction to be the first statement with in the constructor.

Passing 'this' as an argument in the constructor call/method call

Since this in Java refers to the current object so this can be used as an argument where ever current object is needed.

public class A {
 void anotherMethod(A obj){  
  System.out.println("In anotherMethod");  
 }  
 void displayData(){  
  anotherMethod(this);  
 }  
 public static void main(String args[]){  
  A a = new A();  
  a.displayData();  
 }  
}

this keyword used to call methods of a class

Since this in Java refers to the current object so this can also be used to call methods of the class.

public class A {
 void anotherMethod(){  
  System.out.println("In anotherMethod");  
 }  
 void displayData(){  
  this.anotherMethod();
  this.toString();
 }  
 public static void main(String args[]){  
  A a = new A();  
  a.displayData();  
 }  
}

That's all for this topic this Keyword in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. final Keyword in Java With Examples
  2. super Keyword in Java With Examples
  3. Constructor in Java
  4. static Keyword in Java With Examples
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. strictfp in Java
  2. Constructor Chaining in Java
  3. Varargs (Variable-length Arguments) in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. How ArrayList Works Internally in Java
  6. Interface Default Methods in Java
  7. Method Reference in Java
  8. Check if Given String or Number is a Palindrome Java Program