Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Objects and Classes in Java

The document provides an overview of objects and classes in Java, emphasizing their fundamental roles in object-oriented programming (OOP). It defines objects as real-world entities with state, behavior, and identity, while classes serve as blueprints for creating objects. The document also discusses various aspects of classes, such as fields, methods, constructors, and different ways to create and initialize objects.

Uploaded by

logesh ramesh92
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Objects and Classes in Java

The document provides an overview of objects and classes in Java, emphasizing their fundamental roles in object-oriented programming (OOP). It defines objects as real-world entities with state, behavior, and identity, while classes serve as blueprints for creating objects. The document also discusses various aspects of classes, such as fields, methods, constructors, and different ways to create and initialize objects.

Uploaded by

logesh ramesh92
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Objects and Classes in Java

In object oriented programming, object and class plays vital role in programming. These are the
two main pillars of OOP. Without object and class, we cannot create a program in Java. So, in
this section, we are going to discuss about objects and classes in Java.

What is an object in Java?

Object in Java

An object is a real-word entity that has state and behaviour. In other words, an object is a
tangible thing that can be touch and feel, like a car or chair, etc. are the example of objects. The
banking system is an example of an intangible object. Every object has a distinct identity, which
is usually implemented by a unique ID that the JVM uses internally for identification.

Characteristics of an Object:

State: It represents the data (value) of an object.

Behavior: It represents the behavior (functionality) of an object such as deposit, withdraw, etc.

Identity: An object's identity is typically implemented via a unique ID. The ID's value is not
visible to the external user; however, it is used internally by the JVM to identify each object
uniquely.

Characteristics of Object in Java


For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:

An object is a real-world entity.

An object is a runtime entity.

The object is an entity which has state and behavior.

The object is an instance of a class.

What is a Class in Java?

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

Class in Java

1. Fields

Variables stated inside a class that indicate the status of objects formed from that class are called
fields, sometimes referred to as instance variables. They specify the data that will be stored in
each class object. Different access modifiers, such as public, private, and protected, can be
applied to fields to regulate their visibility and usability.

2. Methods

Methods are functions defined inside a class that includes the actions or behaviors that objects of
that class are capable of performing. These techniques allow the outside world to function and
change the object's state (fields). Additionally, methods can be void (that is, they return nothing)
or have different access modifiers. They can also return values.

3. Constructors

Constructors are unique methods that are used to initialize class objects. When an object of the
class is created using the new keyword, they are called with the same name as the class.
Constructors can initialize the fields of an object or carry out any additional setup that's required
when an object is created.

4. Blocks

Within a class, Java allows two different kinds of blocks: instance blocks, commonly referred to
as initialization blocks and static blocks. Static blocks, which are usually used for static
initialization, are only executed once when the class is loaded into memory. Instance blocks can
be used to initialize instance variables and are executed each time a class object is generated.

5. Nested Class and Interface

Java permits the nesting of classes and interfaces inside other classes and interfaces. The
members (fields, methods) of the enclosing class are accessible to nested classes, which can be
static or non-static. Nested interfaces can be used to logically group related constants and
methods together because they are implicitly static.

Syntax of a Class

class <class_name>{

field;

method;

Instance Variable in Java

A variable created inside the class but outside the method is known as an instance variable. An
instance variable does not get memory at compile time; it gets memory at runtime when an
object or instance is created.

Each class instance has its own copy of instance variables, which means that changes made to
instance variables of one object do not affect the values of instance variables in other objects of
the same class. Moreover, setter methods and constructors can be used to initialize them. In
object-oriented programming, instance variables are crucial for encapsulating data within objects
since they are frequently used to represent the state or properties of objects.
Method in Java

In Java method is a block of code inside a class that's intended to carry out a certain function. To
provide a mechanism to interact with the state of an object and to encapsulate behaviour within
objects, methods are required.

Advantages of Methods

Code Reusability: Methods encourage code reusability by permitting the same block of code to
be used repeatedly inside a program. Once defined, a method can be called from any area of the
program where it is available.

Code Optimization: Methods allow for code optimization by enclosing intricate or repetitive
functionality into reusable components. The modularization of logic facilitates readability and
simplifies code maintenance.

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in the Heap
memory area.

In Java, an instance of a class-also referred to as an object-is created using the new keyword. The
new keyword dynamically allocates memory for an object of that class and returns a reference to
it when it is followed by the class name and brackets with optional arguments.

MyClass.java

public class MyClass {

int myField;

public MyClass(int value) {

myField = value;

public static void main(String[] args) {

// Using the new keyword to create an instance of MyClass

MyClass myObject = new MyClass(10);

// Accessing the instance variable of the object

System.out.println("Value of myField: " + myObject.myField);

}
}

Output:

Value of myField: 10

Object and Class Example: main within the class

In Java, the main() method can be declared in a class, which is typically done in demonstration
or basic programs. Having the main() method defined inside of a class allows a program to run
immediately without creating a separate class containing it.

In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

//Java Program to illustrate how to define a class and fields

//Defining a Student class.

class Student{

//defining fields

int id;//field or data member or instance variable

String name;

//creating main method inside the Student class

public static void main(String args[]){

//Creating an object or instance

Student s1=new Student();//creating an object of Student

//Printing values of the object

System.out.println(s1.id);//accessing member through reference variable

System.out.println(s1.name);

}
Output:

null

Object and Class Example: main() Method Outside the Class

In real-world development, it is usual practice to organise Java classes into distinct files and to
place the main method outside of the class it is intended to execute from. This strategy improves
the readability, maintainability, and reusability of the code.

In real time development, we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example, where we are having main() method in another
class.

We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.

File: TestStudent1.java

//Java Program to demonstrate having the main method in

//another class

//Creating Student class.

class Student{

int id;

String name;

//Creating another class TestStudent1 which contains the main method

class TestStudent1{

public static void main(String args[]){

Student s1=new Student();

System.out.println(s1.id);
System.out.println(s1.name);

Output:

null

Explanation

Initializing Object in Java

There are the following three ways to initialize object in Java.

By reference variable,By method,By constructor

1) Initialization through Reference Variable

Initializing an object means storing data in the object. Let's see a simple example where we are
going to initialize the object through a reference variable.

File: TestStudent2.java

class Student{

int id;

String name;

class TestStudent2{

public static void main(String args[]){

Student s1=new Student();

s1.id=101;

s1.name="Sonoo";

System.out.println(s1.id+" "+s1.name);//printing members with a white space

}
}

Output:

101 Sonoo.

We can also create multiple objects and store information in it through reference variable.

File: TestStudent3.java

class Student{

int id;

String name;

class TestStudent3{

public static void main(String args[]){

//Creating objects

Student s1=new Student();

Student s2=new Student();

//Initializing objects

s1.id=101;

s1.name="Sonoo";

s2.id=102;

s2.name="Amit";

//Printing data

System.out.println(s1.id+" "+s1.name);

System.out.println(s2.id+" "+s2.name);

Output:
101 Sonoo

102 Amit

2) Initialization through Method

In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method.

Here, we are displaying the state (data) of the objects by invoking the displayInformation()
method.

File: TestStudent4.java

class Student{

int rollno;

String name;

void insertRecord(int r, String n){

rollno=r;

name=n;

void displayInformation(){System.out.println(rollno+" "+name);}

class TestStudent4{

public static void main(String args[]){

Student s1=new Student();

Student s2=new Student();

s1.insertRecord(111,"Karan");

s2.insertRecord(222,"Aryan");

s1.displayInformation();

s2.displayInformation();

}
}

Output:

111 Karan

222 Aryan

Object in Java with values

As we can see in the above figure, the object gets the memory in the heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 are
reference variables that refer to the objects allocated in memory.

3) Initialization through a Constructor

The concept of object initialization through a constructor is essential to object-oriented


programming in Java. Special methods inside a class called constructors are called when an
object of that class is created with the new keyword. They initialise the state of objects by
entering initial values in their fields or carrying out any required setup procedures. The
constructor is automatically invoked upon object instantiation, guaranteeing correct initialization
of the object prior to usage.

Here's an example demonstrating object initialization through a constructor:

File: ObjectConstructor.java

class Student {

int id;

String name;
// Constructor with parameters

public Student(int id, String name) {

this.id = id;

this.name = name;

// Method to display student information

public void displayInformation() {

System.out.println("Student ID: " + id);

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

public class ObjectConstructor {

public static void main(String[] args) {

// Creating objects of Student class with constructor

Student student1 = new Student(1, "John Doe");

Student student2 = new Student(2, "Jane Smith");

// Displaying information of the objects

student1.displayInformation();

student2.displayInformation();

Output:

Student ID: 1

Student Name: John Doe

Student ID: 2
Student Name: Jane Smith

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

class Employee{

int id;

String name;

float salary;

void insert(int i, String n, float s) {

id=i;

name=n;

salary=s;

void display(){System.out.println(id+" "+name+" "+salary);}

public class TestEmployee {

public static void main(String[] args) {

Employee e1=new Employee();

Employee e2=new Employee();

Employee e3=new Employee();

e1.insert(101,"ajeet",45000);

e2.insert(102,"irfan",25000);

e3.insert(103,"nakul",55000);

e1.display();

e2.display();
e3.display();

Output:

101 ajeet 45000.0

102 irfan 25000.0

103 nakul 55000.0

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java

class Rectangle{

int length;

int width;

void insert(int l, int w){

length=l;

width=w;

void calculateArea(){System.out.println(length*width);}

class TestRectangle1{

public static void main(String args[]){

Rectangle r1=new Rectangle();

Rectangle r2=new Rectangle();

r1.insert(11,5);

r2.insert(3,15);
r1.calculateArea();

r2.calculateArea();

Output:

55

45

There are the following ways to create an object in Java.

1. By new keyword

The most common way to create an object in Java is by using the new keyword followed by a
constructor.

For example: ClassName obj = new ClassName();. This allocates memory for the object and
calls its constructor to initialize it.

2. By newInstance() method

This method is part of the java.lang.Class class and is used to create a new instance of a class
dynamically at runtime. It invokes the no-argument constructor of the class.

For example: ClassName obj = (ClassName) Class.forName("ClassName").newInstance();.

3. By clone() method

The clone() method creates a copy of an existing object by performing a shallow copy. It returns
a new object that is a duplicate of the original object. For example: ClassName obj2 =
(ClassName) obj1.clone();.

4. By deserialization

Objects can be created by deserializing them from a stream of bytes. This is achieved using the
ObjectInputStream class in Java. The serialized object is read from a file or network, and then
the readObject() method is called to recreate the object.

5. By factory method

Factory methods are static methods within a class that return instances of the class. They provide
a way to create objects without directly invoking a constructor and can be used to encapsulate
object creation logic.
For example: ClassName obj = ClassName.createInstance().

We will learn these ways to create object later.

Different Ways to create an Object in Java

Anonymous Object

Anonymous simply means nameless. An object which has no reference is known as an


anonymous object. It can be used at the time of object creation only.

If we have to use an object only once, an anonymous object is a good approach. For example:

new Calculation();//anonymous object

Calling method through a reference:

Calculation c=new Calculation();

c.fact(5);

Calling method through an anonymous object

new Calculation().fact(5);

Let's see the full example of an anonymous object in Java.

class Calculation{

void fact(int n){

int fact=1;

for(int i=1;i<=n;i++){

fact=fact*i;

System.out.println("factorial is "+fact);

public static void main(String args[]){

new Calculation().fact(5);//calling method with anonymous object

}
}

Output:

Factorial is 120

Creating Multiple Objects by One Type Only

We can create multiple objects by one type only as we do in case of primitives.

Initialization of Primitive Variables

int a=10, b=20;

Initialization of Reference Variables

Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

Let's see the example:

//Java Program to illustrate the use of Rectangle class which

//has length and width data members

class Rectangle{

int length;

int width;

void insert(int l,int w){

length=l;

width=w;

void calculateArea(){System.out.println(length*width);}

class TestRectangle2{

public static void main(String args[]){

Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

r1.insert(11,5);
r2.insert(3,15);

r1.calculateArea();

r2.calculateArea();

} }

Output:

55

45

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that we can create new classes that are built upon existing
classes. When we inherit methods from an existing class, we can reuse methods and fields of the
parent class. However, we can add new methods and fields in your current class also.

What is Inheritance?

Inheritance in Java enables a class to inherit properties and actions from another class, called a
superclass or parent class. A class derived from a superclass is called a subclass or child group.
Through inheritance, a subclass can access members of its superclass (fields and methods),
enforce reuse rules, and encourage hierarchy.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in Java?

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.

Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that we are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class that is inherited is called a parent or superclass, and the new
class is called child or subclass.

Java Inheritance Example

Inheritance in Java

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

File Name: Programmer.java


class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

Programmer salary is:40000.0

Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of Inheritance in Java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Types of inheritance in Java

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Multiple inheritance in Java

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

class Animal{

void eat(){System.out.println("eating...");}
}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

}}

Output:

barking...

eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class BabyDog extends Dog{

void weep(){System.out.println("weeping...");}
}

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();

d.weep();

d.bark();

d.eat();

}}

Output:

weeping...

barking...

eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: TestInheritance3.java

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class Cat extends Animal{

void meow(){System.out.println("meowing...");}

}
class TestInheritance3{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat();

//c.bark();//C.T.Error

}}

Output:

meowing...

eating...

Access Modifier with Method Overriding

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.

Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.

Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package outside package
by subclass only
PRIVATE Y N N N
DEFAULT Y Y N N
PROTECTED Y Y Y N
PUBLIC Y Y Y Y

1) Private The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is a compile-time error.

class A{

private int data=40;

private void msg(){System.out.println("Hello java");}

public class Simple{

public static void main(String args[]){

A obj=new A();

System.out.println(obj.data);//Compile Time Error

obj.msg();//Compile Time Error

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

class A{
private A(){}//private constructor

void msg(){System.out.println("Hello java");}

public class Simple{

public static void main(String args[]){

A obj=new A();//Compile Time Error

Note: A class cannot be private or protected except nested class.

2) Default If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by A.java

package pack;

class A{

void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();//Compile Time Error


obj.msg();//Compile Time Error

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) Protected The protected access modifier is accessible within package and outside the package
but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java

package pack;

public class A{

protected void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B extends A{

public static void main(String args[]){

B obj = new B();

obj.msg();

}
}

Output:Hello

4) Public The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

Example of public access modifier

//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Output: Hello

Difference Between this and super in Java

The 'this' and the 'super' keywords are reserved words that are used in a different context.
Besides this, Java also provides this() and super() constructors that are used in the constructor
context. In this section, we will discuss the differences between this and super keyword and
this() and super() constructor, in Java.

super keyword and super() constructor


super Keyword

A reserved keyword used to call the base class method or variable is known as a super keyword.
We cannot use the super keyword as an identifier. The super keyword is not only used to refer to
the base class instance but also static members too.

super() Constructor

The super() is mainly used for invoking base class member functions and constructors.

Let's take an example of both the super keyword and super() to understand how they work.

SuperExample1.java

// import required classes and packages

package javaTpoint.MicrosoftJava;

// create Animal class which is base class of Animal

class Animal{

// data member of Animal class

String color = "white";

// create child class of Animal

class Cat extends Animal{

//default constructor

Cat()

// data members of the Cat class


String color = "Brown";

System.out.println("The cat is of color "+super.color); // calling parent class data member

System.out.println("The cat is of color "+color);

// create child class for Car

class SuperExample1 extendsCat

// default constructor

SuperExample1()

// calling base class constructor

super();

System.out.println("The eyes of the cat is blue.");

// main() method start

publicstaticvoid main(String[] args)

// call default constructor of the SuperExample1

new SuperExample1();

System.out.println("Inside Main");

Output:
this vs super in Java

In the main() method, we have made a statement new SuperExample1(). It calls the constructor
of the SuperExample1 class.

Inside the constructor, we have made statement super() which calls the constructor of its parent
class, i.e., Cat. In the constructor, we have made three statements:

Initialize color with value 'Brown'.

Print parent class data member.

Print current class data member.

When the second statement executes, the flow of the program jumps to Animal class to access
the value of its data members. After accessing it, the flow comes back to the Cat class
constructor and prints it. After that, the last statement executes and prints the value of the
variables of the current class.

After execution of the last statement of the Cat class, the flow comes back to the constructor of
class SuperExample1 and executes the remaining statements.

After completing the execution of the SuperExample1(), the flow comes back to the main()
method and executes the remaining statements.

Note: In order to use the super(), we have to make sure that it should be the first statement in the
constructor of a class. We can use it to refer only to the parent class constructor.

this keyword and this() constructor

this keyword

It is a reserved keyword in Java that is used to refer to the current class object. It is a reference
variable through which the method is called. Other uses of this keyword are:

We can use it to refer current class instance variable.


We can use it to invoke the current class method (implicitly).

We can pass it as an argument in the method and constructor calls.

We can also use it for returning the current class instance from the method.

this() Constructor

The constructor is used to call one constructor from the other of the same class. Let's take an
example of both this keyword and this() to understand how they work.

ThisExample1.java

// import required classes and packages

package javaTpoint.MicrosoftJava;

// create ThisExample1 class to understand the working of this() and this

class ThisExample1 {

// initialize instance and static variable

int x = 5;

staticinty = 10;

// default constructor of class ThisExample1

ThisExample1()

// invoking current class constructor

this(5);

System.out.println("We are insie of the default constructor.");


System.out.println("The value of x = "+x);

ThisExample1(int x)

this.x = x; // override value of the current class instance variable

System.out.println("We are inside of the parameterized constructor.");

System.out.println("The value of y = "+y);

publicstaticvoid main(String[] args)

// invoking constructor of the current class

new ThisExample1();

System.out.println("Inside Main");

Output:

this vs super in Java

Difference Between this and super keyword

The following table describes the key difference between this and super:

this

super

The current instance of the class is represented by this keyword.


The current instance of the parent class is represented by the super keyword.

In order to call the default constructor of the current class, we can use this keyword.

In order to call the default constructor of the parent class, we can use the super keyword.

It can be referred to from a static context. It means it can be invoked from the static context.

It can't be referred to from a static context. It means it cannot be invoked from a static context.

We can use it to access only the current class data members and member functions.

We can use it to access the data members and member functions of the parent class.

Difference Between this() and super() Constructor

this()

super()

The this() constructor refers to the current class object.

The super() constructor refers immediate parent class object.

It is used for invoking the current class method.

It is used for invoking parent class methods.

It can be used anywhere in the parameterized constructor.

It is always the first line in the child class constructor.

It is used for invoking a super-class version of an overridden method.

It is used for invoking a super-class version of an overridden method.

You might also like