1.

Java Keywords

Answer»

a) Understanding the this keyword in Java:

The this keyword in java can be used in multiple ways. The following are the use cases of the this keyword:

this: to refer to the current instance variable of the class

The this keyword can be used to refer to the current instance variable of a class. If there is any ambiguity between the instance variables and arguments, this keyword clears things out.

Example -

class Sample{
int a;
Sample(int a){
this.a=a;
}
void display(){
System.out.println("a = "+a);
}
}

class Test{
public static void main(String args[]){
Sample s1=new Sample(10);
s1.display();
}
}

Output -

a = 10

Explanation: In the above code, we can see that both the data member of the class Sample and the parameter of the constructor of the Sample class have the same name ‘a’. Here, we use the this keyword to differentiate between the two.

this: to call the method of the current class

The this keyword can be used to call a method in the current class. If you don't use this keyword, the compiler will add it for you when you call the method. Let's look at an example.

class Sample{
void fun()
{
System.out.println("hello there");
}
void foo(){
System.out.println("hello foo");
this.fun();
}
}
class Test{
public static void main(String args[]){
Sample s = new Sample();
s.foo();
}
}

Output -

hello foo
hello there

Explanation - In the above code, we have 2 methods defined in the Sample class fun and foo. We create an instance of the Sample class and call the method foo(). In the foo() method, we call the fun() method using this keyword. 

this() is used to call the constructor of the current class

The current class constructor can be called using the this() call. It allows for constructor chaining.

Example -

class Sample{
Sample()
{
System.out.println("In default constructor");
}
Sample(int a)
{
this();
System.out.println("In Parameterised constructor");
}
}
class Test{
public static void main(String args[]){
Sample s = new Sample(10);
}
}

Explanation - In the above code, we have two constructors defined in the Sample class. We call the default constructor from the parameterised constructor using the this() statement. 

this: to use as a parameter in a method

The keyword this can also be used as an argument in a method. It is primarily used in event handling. Let's look at an example:

class Sample{
void fun(Sample obj)
{
System.out.println("Received the object");
}
void foo(){
fun(this); 
}
}
class Test{
public static void main(String args[]){
Sample s = new Sample();
s.foo();
}
}

In the above code, two functions fun and foo have been defined in the Sample class. The function fun() accepts a parameter of Sample object type. We call the function fun() from the function foo() and pass this as a reference to the current invoking object.

this keyword can be used to get the current instance of a class

This keyword can be returned as a statement from the method. In this situation, the method's return type must be the class type (non-primitive). Let's look at an example:

class Sample{
Sample getObject()
{
return this;
}
void foo(){
System.out.println("Inside foo function")
}
}
class Test{
public static void main(String args[]){
Sample s = new Sample();
s.getObject().foo();
}
}

Output -

Inside foo function

In the above code, we have a function ‘getObject’ defined in the Sample class which returns a reference to the current invoking object. We use this reference returned to call the foo() method from the Test class.

b) final keyword in Java:

The final keyword is used in a variety of situations. To begin with, final is a non-access modifier that only applies to variables, methods, and classes. The behaviour of final in each scenario is listed below:

Final Variables:
When a variable is declared using the final keyword, the value of the variable cannot be changed, making it a constant. This also necessitates the creation of a final variable. If the final variable is a reference, it cannot be re-bound to reference another object, but the internal state of the object indicated by that reference variable can be altered, allowing you to add or delete elements from the final array or collection.

Example -

final int temp = 10;

Final Classes:

A final class is one that has been declared with the final keyword. It is not possible to extend a final class. A final class can be used in two ways:


  • The first is to avoid inheritance because final classes cannot be extended. All Wrapper Classes, such as Integer, Float, and others, are final classes. We are unable to extend them.

  • The final keyword can also be used with classes to construct immutable classes, such as the String class. It is impossible to make a class immutable without making it final.

Example -

final class Sample
{
// code
}
class Test extends Sample // COMPILE-ERROR!

// code 
}

The above code gives a compile-time error. The reason is that the class Sample is declared as final and since the class Test is trying to extend the Sample class, it gives a compile-time error.

Final Methods:

A method is called a final method when it is declared with the final keyword. It is not possible to override a final method. In the Object class, many methods defined are declared final. This is done so that a user cannot modify the definition of those functions in their java classes. We must use the final keyword to declare methods for which we must use the same implementation throughout all derived classes.

Example -

class Sample
{
final void fun()
{
System.out.println("Inside fun function");
}
}
class Test extends Sample 

void fun() // COMPILE-ERROR!
{
//code
}
}

The above code on execution gives a compile-time error. The reason is that the fun() function declared in the Sample class is a final method so we cannot override it in the inherited class. In the above code, the Test class tries to override the fun() function defined in the Sample class and this leads to a compilation error.

c) static keyword in Java:

In Java, the static keyword is mostly used to control memory. In Java, the static keyword is used to share a class's variable or method. Static keywords can be used with variables, methods, blocks, and nested classes. The static keyword refers to a class rather than a specific instance of that class. 

The static keyword is used in the following ways:

Static Blocks:

You can declare a static block that gets executed exactly once when the class is first loaded if you need to do the computation to initialise your static variables.

Consider the Java program below, which demonstrates the use of static blocks.

class Test
{
static int x = 25;
static int y;

// static block
static {
System.out.println("Inside Static block.");
y = x * 4;
}

public static void main(String[] args)
{
System.out.println("Value of x : " + x);
System.out.println("Value of y : " + y);
}
}

Output -

Inside Static block.
Value of x : 25
Value of y : 100

Explanation - In the above code, there are 2 static variables x and y. X is initialised with 25. We can see that first of all, the static block is executed which prints the statement “Inside Static block.” and initialises y to x * 4 (i.e., 100).

Static Variables:

When a variable is marked as static, a single copy of the variable is made at the class level and shared among all objects. Static variables are effectively global variables. The static variable is shared by all instances of the class.  In a program, static blocks and static variables are executed in the order in which they appear.

Example -

class Test
{
// static variable
static int x = fun();

// static block
static {
System.out.println("Inside static block");
}

// static method
static int fun() {
System.out.println(Inside fun function");
return 10;
}

public static void main(String[] args)
{
System.out.println("Value of x : " + x);
System.out.println("Inside main method");
}
}

Output -

Inside fun function
Inside static block
Value of x : 10
Inside main method

Explanation - In the above code, first of all, x gets initialised by calling the fun() function. Hence, the statement “Inside fun function” gets printed. Then, the static block gets executed since it is after the initialisation of x statement. At last, the statements inside the main method get printed.

Static Methods:

The static method is defined as a method that is declared using the static keyword. The main() method is the most common example of a static method. Any static member of a class can be accessed before any objects of that class are generated, and without requiring a reference to any object. Static methods are subject to the following constraints:


  • They can only call other static methods directly.

  • They can only access static data directly.

  • They are not allowed to use the words "this" or "super" in any way.

Example -

class Test
{

static int x = 1; // static variable
int y = 20; // instance variable


static void fun() // static method
{
x = 20;
System.out.println("Inside fun function");

y = 10; // compilation error since there is a static reference to the non-static field b

foo(); // compilation error since there is a static reference to the non-static method foo()

System.out.println(super.a); // compilation error since we cannot use super in a static context
}

void foo() // instance method
{
System.out.println("Inside foo function");
}
public static void main(String[] args)
{
// main method 
}
}

The above code results in a compilation error. There are 3 reasons for it.


  • We are accessing an instance variable inside a static method and changing its value.

  • We are invoking an instance method inside a static method.

  • We are trying to make use of the super keyword inside a static method.

Static Classes:

When a class is declared with the static keyword, it is said to be a static class. A class can be made static in Java if and only if it is nested inside another class. We can't use the static modifier on top-level classes, but we can use it on nested classes. 

Example -

public class Test {

private static String str = "Interview bit";

// Static class
static class Sample {

public void display(){ 
System.out.println(str); 
}
}

public static void main(String args[])
{
Test.Sample obj
= new Test.Sample();
obj.display();
}
}

Output -

Interview bit

Explanation - In the above code, we have a static nested class named ‘Sample’ inside the ‘Test’ class. We create an object of the Sample class and call the display function.

d) super keyword in Java: 

In Java, the super keyword is a reference variable that refers to parent class instances. With the concept of Inheritance, the term "super" entered the picture. It's most commonly used in the following situations:

Using super with variables:

When a derived class and a base class have identical data members, there is uncertainty for the JVM as to which class’s data member is being referred to. In order to resolve this ambiguity, we use the super keyword with the data member’s name. This code snippet will help us comprehend it better:

class Sample1
{
int x = 1;
}

class Sample2 extends Sample1
{
int x = 2;

void display()
{
System.out.println("The value of x is : " + super.x);
}
}

class Test
{
public static void main(String[] args)
{
Sample2 s = new Sample2();
s.display();
}
}

Output -

The value of x is : 1

Explanation - In the above code both the classes, Sample1 and Sample2 have a data member named ‘x’. We use the super keyword inside the display function of the Sample2 class to access the data member x of the parent class Sample1.

Using super with methods:

To resolve ambiguity when a parent and child class have the same-named methods, we employ the super keyword. This code snippet demonstrates how to use the super keyword.

class Sample1
{
void fun()
{
System.out.println("Inside Sample1's fun method");
}
}

class Sample2 extends Sample1
{
void fun()
{
System.out.println("Inside Sample2's fun method");
}

void display()
{
super.fun();
}
}

class Test
{
public static void main(String[] args)
{
Sample2 s = new Sample2();
s.display();
}
}

Output -

Inside Sample1's fun method

Explanation - In the above code, both the classes Sample1 and Sample2 have a method named fun. However, in the display method of the Sample2 class, the statement “Inside Sample1’s fun method” gets printed because of the super keyword.

Use of the super keyword with constructors: 

The super keyword can also be used to access the constructor of the parent class. Another key point to note is that, depending on the situation, 'super' can refer to both parametric and non-parametric constructors. The following is a code snippet to demonstrate the concept:

class Sample1
{
Sample1()
{
System.out.println("Inside Sample1's default constructor.")
}
}

class Sample2 extends Sample1
{
Sample2()
{
super();
System.out.println("Inside Sample2's default constructor.");
}
}

class Test
{
public static void main(String[] args)
{
Sample2 s = new Sample2();
}
}

Output -

Inside Sample1's default constructor.
Inside Sample2's default constructor.

Explanation - In the above code, the class Sample2 extends the class Sample1. We invoke the constructor of the Sample1 class in the constructor of the Sample2 class by using the super keyword. Hence, when we create an instance of the Sample2 class, both the statements get printed.




Discussion

No Comment Found