0% found this document useful (0 votes)
3 views

OOP's concept of oops in programing

Java packages are used to group related classes and avoid naming conflicts, categorized into built-in and user-defined packages. The Java API provides a library of prewritten classes for various functionalities, and access modifiers control the visibility of classes and methods. Abstract classes and interfaces are used for abstraction, with interfaces supporting multiple inheritance to resolve the diamond problem in Java.

Uploaded by

ui21ec63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

OOP's concept of oops in programing

Java packages are used to group related classes and avoid naming conflicts, categorized into built-in and user-defined packages. The Java API provides a library of prewritten classes for various functionalities, and access modifiers control the visibility of classes and methods. Abstract classes and interfaces are used for abstraction, with interfaces supporting multiple inheritance to resolve the diamond problem in Java.

Uploaded by

ui21ec63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Java Packages

Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file


directory. We use packages to avoid name conflicts, and to write a better maintainable
code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

 The Java API is a library of prewritten classes, that are free to use, included in the
Java Development Environment.

 The library contains components for managing input, database programming, and
much much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.

 The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that
contain all the classes that belong to the specified package.

 A java package is a group of similar types of classes, interfaces and sub-


packages.
 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
 Here, we will have the detailed learning of creating and using user-defined
packages.
 Advantage of Java Package
 1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
 2) Java package provides access protection.
 3) Java package removes naming collision.

 To use a class or a package from the library, you need to use


the import keyword:
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package

If you find a class you want to use, for example, the Scanner class, which is used to
get user input, write the following code:

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of


the java.util package.

To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

Output:
Enter username
Abc
Username is: Abc

import a Package

we used the Scanner class from the java.util package. This package also contains
date and time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:

import java.util.*;

User-defined Packages

To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:

└── root
└── mypack
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java

package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Save the file as MyPackageClass.java, and compile it:

C:\Users\ your name>javac MyPackageClass.java


Then compile the package:
C:\Users\your name>javac –d . MyPackageClass.java

This forces the compiler to create the "mypack" package.

The -d keyword specifies the destination for where to save the class file. You can use
any directory name, like c:/user (windows), or, if you want to keep the package within
the same directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class
names.

When we compiled the package in the example above, a new folder was created, called
"mypack".

To run the MyPackageClass.java file, write the following:

C:\Users\Your Name>java mypack.MyPackageClass


The output will be:

This is my package!

Simple example of java package


The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple


Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

Access Modifiers in Java


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:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. 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.
3. 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.
4. 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

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

The private access modifier is accessible only within the class.

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.

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.

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

Abstract Class in Java.


Abstract class in Java is similar to interface except that it can contain default method
implementation. An abstract class can have an abstract method without body and it can
have methods with implementation also. abstract keyword is used to create a abstract
class and method.

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of
the method.
Syntax:

abstract class A{}


abstract void printStatus();//no method body and abstract

// Example of Abstract class and method


abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output:
running safely
Abstract Methods & class in java
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Syntax:

abstract class A{}

A method which is declared as abstract and does not have implementation is known as an abstract
method.

abstract void print(); //no method body and abstract

//Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike


{
abstract void run();
}
class Honda extends Bike
{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}

Output:
running safely

//Example of abstract method


abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw()
{System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw()
{System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1(); //In a real scenario, object is provided through method i.e.
getShape() method
s.draw();
}
}

Output: drawing circle

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
What is Diamond Problem in Java
In Java, the diamond problem is related to multiple inheritance. Sometimes it is also known
as the deadly diamond problem or deadly diamond of death. In this section, we will
learn what is the demand problem in Java and what is the solution to the diamond
problem.

The Diamond Problem


The diamond problem is a common problem in Java when it comes to inheritance. Inheritance
is a very popular property in an object-oriented programming language, such as C++, Java,
etc. There are different types of inheritance such as, single, multiple, multi-level, and hybrid
inheritance. But remember that Java does not support the multiple inheritance because of
the diamond problem.

The Solution of Diamond Problem


The solution to the diamond problem is default methods and interfaces. We can achieve
multiple inheritance by using these two things.

The default method is similar to the abstract method. The only difference is that it is defined
inside the interfaces with the default implementation. We need not to override these methods.
Because they are already implementing these interfaces.

The advantage of interfaces is that it can have the same default methods with the same name
and signature in two different interfaces. It allows us to implement these two interfaces, from a
class. We must override the default methods explicitly with its interface name.

The "diamond problem" (sometimes referred to as the "Deadly Diamond of Death") is an ambiguity that
arises when two classes B and C inherit from A, and class D inherits from both B and C.

Although Diamond Problem is a serious issue but we can create a solution


for it which is Interface. Interface are created by using interface keyword. It
contains all methods by default as abstract we don't need to declared as
abstract ,compiler will do it implicitly.
 For instance, let us assume that Java does support multiple inheritance.
 And if we have an abstract class named Sample with an abstract method demo().
 Then if two other classes in the same package extends this class and try to
implement its abstract method, demo().
 Then, as per the basic rule of inheritance, a copy of both demo() methods should
be created in the subclass object which leaves the subclass with two methods with
same prototype (name and arguments).
 Then, if you call the demo() method using the object of the subclass compiler
faces an ambiguous situation not knowing which method to call. This issue is
known as diamond problem in Java.

Solution to diamond problem

You can achieve multiple inheritance in Java, using the default methods (Java8) and
interfaces.

From Java8 on wards default methods are introduced in an interface. Unlike other
abstract methods these are the methods of an interface with a default
implementation. If you have default method in an interface, it is not mandatory to
override (provide body) it in the classes that are already implementing this interface.
You can have same default methods (same name and signature) in two different
interfaces and, from a class you can implement these two interfaces.

If you do so, you must override the default method from the class explicitly specifying
the default method along with its interface name.

interface MyInterface1{

public static int num = 100;

public default void display() {

System.out.println("display method of MyInterface1");

interface MyInterface2{

public static int num = 1000;

public default void display() {

System.out.println("display method of MyInterface2");

public class InterfaceExample implements MyInterface1, MyInterface2{

public void display() {

MyInterface1.super.display();

//or,

MyInterface2.super.display();

public static void main(String args[]) {

InterfaceExample obj = new InterfaceExample();

obj.display();

}
Output:

display method of MyInterface1

display method of MyInterface2

import java.util.*;

interface Sample1 {

default void sum(int x,int y) {

System.out.println("Sum 1 is = "+ (x+y));

interface Sample2 {

default void sum(int x,int y) {


System.out.println("Sum 2 is = "+ (x+y));

class Dummy implements Sample1, Sample2{

@Override

public void sum(int x,int y) {

System.out.println("Sum is = "+ (x+y));

public static void main(String args[]){

Dummy obj = new Dummy();

obj.sum(18,92);

Exception handling in java programming


Exception handling is the process of responding to exceptions when a computer program runs. An
exception occurs when an unexpected event happens that requires special processing.

Difference between Checked and Unchecked Exceptions


1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are known
as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler
at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored, the programmer should take care of (handle) these exceptions.

Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution.
These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or
improper use of an API. Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

The Exception class has two main subclasses: IOException class and RuntimeException Class.

The try statement allows you to define a block of code to be tested for errors while it
is being executed.

The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.

The try and catch keywords come in pairs:

The finally statement lets you execute code, after try...catch, regardless of the
result

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many
exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityEx
ception, etc.

Java Exception class Hierarchy


After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block.
All exception classes in Java extend the class ‘Throwable’. Throwable has two
subclasses, Error and Exception

 The Error class defines the exception or the problems that are not expected
to occur under normal circumstances by our program, example Memory error,
Hardware error, JVM error, etc
 The Exception class represents the exceptions that can be handled by our
program, and our program can be recovered from this exception using try and
catch block
 A Runtime exception is a sub-class of the exception class. The Exception of
these type represents exception that occur at the run time and which cannot
be tracked at the compile time. An excellent example of same is divide by
zero exception, or null pointer exception, etc
 IO exception is generated during input and output operations
 Interrupted exceptions in Java, is generated during multiple threading.

Following is a list of most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods

Following is the list of important methods available in the Throwable class.

Sr.No. Method & Description

1
public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized
in the Throwable constructor.

2
public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.

3
public String toString()
Returns the name of the class concatenated with the result of getMessage().

4
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output
stream.

5
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the method at
the bottom of the call stack.

6
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A try/catch block
is placed around the code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch looks like the following −

Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like
the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}

The Throws/Throw Keywords


If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by
using the throw keyword.

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}

Note the following −


 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.

Common Exceptions
In Java, it is possible to define two catergories of Exceptions and Errors.
 JVM Exceptions − These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException.
 Programmatic Exceptions − These exceptions are thrown explicitly by the application or the
API programmers. Examples: IllegalArgumentException, IllegalStateException.

Difference between final, finally and finalize


There are many differences between final, finally and finalize. A list of differences between final,
finally and finalize are given below:

No. final finally finalize


1) Final is used to apply Finally is used to Finalize is used to
restrictions on class, method place important perform clean up
and variable. Final class can't code, it will be processing just
be inherited, final method can't executed whether before object is
be overridden and final variable exception is handled garbage collected.
value can't be changed. or not.

2) Final is a keyword. Finally is a block. Finalize is a


method.

Inheritance in java

The process by which one class acquires the properties (data members) and
functionalities(methods) of another class is called inheritance.

The aim of inheritance is to provide the reusability of code so that a class has to write
only the unique features and rest of the common properties and functionalities can be
extended from the another class.

Child Class:
The class that extends the features of another class is known as child class, sub class or
derived class.

Parent Class:
The class whose properties and functionalities are used(inherited) by another class is
known as parent class, super class or Base class.

Inheritance is a process of defining a new class based on an existing class by extending


its common data members and methods.

Inheritance allows us to reuse of code, it improves reusability in our java application.


Note: The biggest advantage of Inheritance is that the code that is already present in
base class need not be rewritten in the child class.

This means that the data members(instance variables) and methods of the parent class
can be used in the child class as.

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class XYZ is child class and class ABC
is parent class. The class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC


{
}

Inheritance Example

class Teacher {
String designation = "Teacher";
String collegeName = "Book";
void does(){
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:

Book
Teacher
Physics
Teaching

Types of inheritance

Single Inheritance: refers to a child and parent class relationship where a class extends
the another class.

Multilevel inheritance: refers to a child and parent class relationship where a class
extends the child class. For example class C extends class B and class B extends class A.

Hierarchical inheritance: refers to a child and parent class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same
class A.

Multiple Inheritance: refers to the concept of one class extending more than one
classes, which means a child class has two parent classes. For example class C extends
both classes A and B. Java doesn’t support multiple inheritance,

Hybrid inheritance: Combination of more than one types of inheritance in a single


program. For example class A & B extends class C and another class D extends class A
then this is a hybrid inheritance example because it is a combination of single and
hierarchical inheritance.

Inheritance and Method Overriding

class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
void disp(){
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample(){
System.out.println("Constructor of Child");
}
void disp(){
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(String args[]){
//Creating the object of child class
JavaExample obj = new JavaExample();
obj.disp();
}
}
The output is :

Constructor of Parent
Constructor of Child
Child Method
Parent Method

Interface
An interface is just like Java Class, but it only has static constants and abstract method. Java uses
Interface to implement multiple inheritance. A Java class can implement multiple Java Interfaces. All
methods in an interface are implicitly public and abstract.

An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.

Java Interface also represents the IS-A relationship.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loos
o e coupling.
Syntax for Declaring Interface

interface <interface_name>
{

// declare constant fields


// declare methods that abstract
// by default.
}

To use an interface in your class, append the keyword "implements" after your class name
followed by the interface name.

Example for Implementing Interface

class Dog implements Pet

Difference between Class and Interface

Class Interface

In class, you can instantiate variable In an interface, you can't instantiate


and create an object. variable and create an object.

Class can contain concrete(with The interface cannot contain


implementation) methods concrete(with implementation) methods
The access specifiers used with classes In Interface only one specifier is used-
are private, protected and public. Public.

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

When to use Interface and Abstract Class?


 Use an abstract class when a template needs to be defined for a group of subclasses
 Use an interface when a role needs to be defined for other classes, regardless of the
inheritance tree of these classes

 A Java class can implement multiple Java Interfaces. It is necessary that the class
must implement all the methods declared in the interfaces.
 Class should override all the abstract methods declared in the interface
 The interface allows sending a message to an object without concerning which classes
it belongs.
 Class needs to provide functionality for the methods declared in the interface.
 All methods in an interface are implicitly public and abstract
 An interface cannot be instantiated
 An interface reference can point to objects of its implementing classes
 An interface can extend from one or many interfaces. Class can extend only one class
but implement any number of interfaces
 An interface cannot implement another Interface. It has to extend another interface if
needed.
 An interface which is declared inside another interface is referred as nested interface
 At the time of declaration, interface variable must be initialized. Otherwise, the
compiler will throw an error.
 The class cannot implement two interfaces in java that have methods with same name
but different return type.

Summary:
 The class which implements the interface needs to provide functionality for the
methods declared in the interface
 All methods in an interface are implicitly public and abstract
 An interface cannot be instantiated
 An interface reference can point to objects of its implementing classes
 An interface can extend from one or many interfaces. A class can extend only one
class but implement any number of interfaces

// Example of interface

interface Pet{

public void test();

class Dog implements Pet{

public void test(){

System.out.println("Interface Method Implemented");

public static void main(String args[]){

Pet p = new Dog();

p.test();

Output:

Interface Method Implemented

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.

//example of multiple inheritance using interface


interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");
}

public static void main(String args[])


{
A7 obj = new A7();
obj.print();
obj.show();
}
}

Output: Hello
Welcome

Java Threading
Java is a multi-threaded programming language which means we can develop multi-threaded program
using Java. A multi-threaded program contains two or more parts that can run concurrently and each
part can handle a different task at the same time making optimal use of the available resources
specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources such as a
CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide
specific operations within a single application into individual threads. Each of the threads can run in
parallel. The OS divides processing time not only among different applications, but also among each
thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the
same program.

Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and
then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle −


 New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it completes its task
or otherwise terminates.

Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a
constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which threads
execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface


If your class is intended to be executed as a thread then you can achieve this by implementing
a Runnable interface. You will need to follow three basic steps −

Step 1
As a first step, you need to implement a run() method provided by a Runnable interface. This method
provides an entry point for the thread and you will put your complete business logic inside this method.
Following is a simple syntax of the run() method −
public void run( )

Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is
the name given to the new thread.

Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a call to run(
) method. Following is a simple syntax of start() method −
void start();

// Example of multithreading
class RunnableDemo implements Runnable {

private Thread t;

private String threadName;

RunnableDemo( String name) {

threadName = name;

System.out.println("Creating " + threadName );

public void run() {

System.out.println("Running " + threadName );

try {

for(int i = 4; i > 0; i--) {

System.out.println("Thread: " + threadName + ", " + i);


// Let the thread sleep for a while.

Thread.sleep(50);

} catch (InterruptedException e) {

System.out.println("Thread " + threadName + " interrupted.");

System.out.println("Thread " + threadName + " exiting.");

public void start () {

System.out.println("Starting " + threadName );

if (t == null) {

t = new Thread (this, threadName);

t.start ();

public class TestThread {

public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");

R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");

R2.start();

Output:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Threading Questions
Multithreading and Synchronization are considered as the typical chapter in java
programming. In game development companies, multithreading related interview
questions are asked mostly. A list of frequently asked java multithreading and
concurrency interview questions is given below.

1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Multithreading is
used to obtain the multitasking. It consumes less memory and gives the fast and efficient
performance. Its main advantages are:

o Threads share the same address space.


o The thread is lightweight.
o The cost of communication between the processes is low.

2) What is the thread?


A thread is a lightweight subprocess. It is a separate path of execution because each
thread runs in a different stack frame. A process may contain multiple threads. Threads
share the process resources, but still, they execute independently.

3) Differentiate between process and thread?


There are the following differences between the process and thread.
o A Program in the execution is called the process whereas; A thread is a subset of
the process
o Processes are independent whereas threads are the subset of process.
o Process have different address space in memory, while threads contain a shared
address space.
o Context switching can be faster between the threads as compared to context
switching between the threads.
o Inter-process communication is slower and expensive than inter-thread
communication.
o Any change in Parent process doesn't affect the child process whereas changes in
parent thread can affect the child thread.

4) What do you understand by inter-thread communication?


o The process of communication between synchronized threads is termed as inter-
thread communication.
o Inter-thread communication is used to avoid thread polling in Java.
o The thread is paused running in its critical section, and another thread is allowed to
enter (or lock) in the same critical section to be executed.
o It can be obtained by wait(), notify(), and notifyAll() methods.
5) What is the purpose of wait() method in Java?
The wait() method is provided by the Object class in Java. This method is used for inter-
thread communication in Java. The java.lang.Object.wait() is used to pause the current
thread, and wait until another thread does not call the notify() or notifyAll() method. Its
syntax is given below.

public final void wait()

6) Why must wait() method be called from the synchronized


block?
We must call the wait method otherwise it will
throw java.lang.IllegalMonitorStateException exception. Moreover, we need wait()
method for inter-thread communication with notify() and notifyAll(). Therefore It must be
present in the synchronized block for the proper and correct communication.

7) What are the advantages of multithreading?


Multithreading programming has the following advantages:

o Multithreading allows an application/program to be always reactive for input, even


already running with some background tasks
o Multithreading allows the faster execution of tasks, as threads execute
independently.
o Multithreading provides better utilization of cache memory as threads share the
common memory resources.
o Multithreading reduces the number of the required server as one server can
execute multiple threads at a time.

8) What are the states in the lifecycle of a Thread?


A thread can have one of the following states during its lifetime:

1. New: In this state, a Thread class object is created using a new operator, but the
thread is not alive. Thread doesn't start until we call the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start() method.
However, the thread is not yet selected by the thread scheduler.
3. Running: In this state, the thread scheduler picks the thread from the ready state,
and the thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is
waiting for the other thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when the run()
method exits.

9) What is the difference between preemptive scheduling and


time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting
or dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.

10) What is context switching?


In Context switching the state of the process (or thread) is stored so that it can be
restored and execution can be resumed from the same point later. Context switching
enables the multiple processes to share the same CPU.

11) Differentiate between the Thread class and Runnable


interface for creating a Thread?
The Thread can be created by using two ways.

o By extending the Thread class


o By implementing the Thread class

However, the primary differences between both the ways are given below:
o By extending the Thread class, we cannot extend any other class, as Java does not
allow multiple inheritances while implementing the Runnable interface; we can also
extend other base class(if required).
o By extending the Thread class, each of thread creates the unique object and
associates with it while implementing the Runnable interface; multiple threads
share the same object
o Thread class provides various inbuilt methods such as getPriority(), isAlive and
many more while the Runnable interface provides a single method, i.e., run().

12) What does join() method?


The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task. Join
method is overloaded in Thread class in the following ways.

o public void join()throws InterruptedException


o public void join(long milliseconds)throws InterruptedException

13) Describe the purpose and working of sleep() method.


The sleep() method in java is used to block a thread for a particular time, which means it
pause the execution of a thread for a specific time. There are two methods of doing so.

Syntax:

o public static void sleep(long milliseconds)throws InterruptedException


o public static void sleep(long milliseconds, int nanos)throws InterruptedException

Working of sleep() method

When we call the sleep() method, it pauses the execution of the current thread for the
given time and gives priority to another thread(if available). Moreover, when the waiting
time completed then again previous thread changes its state from waiting to runnable and
comes in running state, and the whole process works so on till the execution doesn't
complete.

14) What is the difference between wait() and sleep() method?


wait() sleep()

1) The wait() method is defined in Object The sleep() method is defined in Thread
class. class.
2) The wait() method releases the lock. The sleep() method doesn't release the
lock.

15) Is it possible to start a thread twice?


No, we cannot restart the thread, as once a thread started and executed, it goes to the
Dead state. Therefore, if we try to start a thread twice, it will give a runtimeException
"java.lang.IllegalThreadStateException".

16) Can we call the run() method instead of start()?


Yes, calling run() method directly is valid, but it will not work as a thread instead it will
work as a normal object. There will not be context-switching between the threads. When
we call the start() method, it internally calls the run() method, which creates a new stack
for a thread while directly calling the run() will not create a new stack.

17) What about the daemon threads?


The daemon threads are the low priority threads that provide the background support and
services to the user threads. Daemon thread gets automatically terminated by the JVM if
the program remains with the daemon thread only, and all other user threads are
ended/died. There are two methods for daemon thread available in the Thread class:

o public void setDaemon(boolean status): It used to mark the thread daemon


thread or a user thread.
o public boolean isDaemon(): It checks the thread is daemon or not.

18)Can we make the user thread as daemon thread if the


thread is started?
No, if you do so, it will throw IllegalThreadStateException.

19)What is shutdown hook?


The shutdown hook is a thread that is invoked implicitly before JVM shuts down. So we
can use it to perform clean up the resource or save the state when JVM shuts down
normally or abruptly. We can add shutdown hook by using the following method:

1. public void addShutdownHook(Thread hook){}


2. Runtime r=Runtime.getRuntime();
3. r.addShutdownHook(new MyThread());

Some important points about shutdown hooks are :


o Shutdown hooks initialized but can only be started when JVM shutdown occurred.
o Shutdown hooks are more reliable than the finalizer() because there are very fewer
chances that shutdown hooks not run.
o The shutdown hook can be stopped by calling the halt(int) method of Runtime
class.

20)When should we interrupt a thread?


We should interrupt a thread when we want to break out the sleep or wait state of a
thread. We can interrupt a thread by calling the interrupt() throwing the
InterruptedException.

21) What is the synchronization?


Synchronization is the capability to control the access of multiple threads to any shared
resource. It is used:

1. To prevent thread interference.


2. To prevent consistency problem.

When the multiple threads try to do the same task, there is a possibility of an
erroneous result, hence to remove this issue, Java uses the process of synchronization
which allows only one thread to be executed at a time. Synchronization can be achieved
in three ways:

o by the synchronized method


o by synchronized block
o by static synchronization

Syntax for synchronized block

1. synchronized(object reference expression)


2. {
3. //code block
4. }
5.

22) What is the purpose of the Synchronized block?


The Synchronized block can be used to perform synchronization on any specific resource
of the method. Only one thread at a time can execute on a particular resource, and all
other threads which attempt to enter the synchronized block are blocked.
o Synchronized block is used to lock an object for any shared resource.
o The scope of the synchronized block is limited to the block on which, it is applied.
Its scope is smaller than a method.

23)Can Java object be locked down for exclusive use by a


given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is
inaccessible to any thread other than the one that explicitly claimed it.

24) What is static synchronization?


If you make any static method as synchronized, the lock will be on the class not on the
object. If we use the synchronized keyword before a method so it will lock the object (one
thread can access an object at a time) but if we use static synchronized so it will lock a
class (one thread can access a class at a time). More details.

25)What is the difference between notify() and notifyAll()?


The notify() is used to unblock one waiting thread whereas notifyAll() method is used to
unblock all the threads in waiting state.

26)What is the deadlock?


Deadlock is a situation in which every thread is waiting for a resource which is held by
some other waiting thread. In this situation, Neither of the thread executes nor it gets the
chance to be executed. Instead, there exists a universal waiting state among all the
threads. Deadlock is a very complicated situation which can break our code at runtime.

27) How to detect a deadlock condition? How can it be


avoided?
We can detect the deadlock condition by running the code on cmd and collecting the
Thread Dump, and if any deadlock is present in the code, then a message will appear on
cmd.

Ways to avoid the deadlock condition in Java:

o Avoid Nested lock: Nested lock is the common reason for deadlock as deadlock
occurs when we provide locks to various threads so we should give one lock to only
one thread at some particular time.
o Avoid unnecessary locks: we must avoid the locks which are not required.
o Using thread join: Thread join helps to wait for a thread until another thread
doesn't finish its execution so we can avoid deadlock by maximum use of join
method.

28) What is Thread Scheduler in java?


In Java, when we create the threads, they are supervised with the help of a Thread
Scheduler, which is the part of JVM. Thread scheduler is only responsible for deciding
which thread should be executed. Thread scheduler uses two mechanisms for scheduling
the threads: Preemptive and Time Slicing.

Java thread scheduler also works for deciding the following for a thread:

o It selects the priority of the thread.


o It determines the waiting time for a thread
o It checks the Nature of thread

29) Does each thread have its stack in multithreaded


programming?
Yes, in multithreaded programming every thread maintains its own or separate stack area
in memory due to which every thread is independent of each other.

30) How is the safety of a thread achieved?


If a method or class object can be used by multiple threads at a time without any race
condition, then the class is thread-safe. Thread safety is used to make a program safe to
use in multithreaded programming. It can be achieved by the following ways:

o Synchronization
o Using Volatile keyword
o Using a lock based mechanism
o Use of atomic wrapper classes

31) What is race-condition?


A Race condition is a problem which occurs in the multithreaded programming when
various threads execute simultaneously accessing a shared resource at the same time.
The proper use of synchronization can avoid the Race condition.

32) What is the volatile keyword in java?


Volatile keyword is used in multithreaded programming to achieve the thread safety, as a
change in one volatile variable is visible to all other threads so one variable can be used
by one thread at a time.
33) What do you understand by thread pool?
o Java Thread pool represents a group of worker threads, which are waiting for the
task to be allocated.
o Threads in the thread pool are supervised by the service provider which pulls one
thread from the pool and assign a job to it.
o After completion of the given task, thread again came to the thread pool.
o The size of the thread pool depends on the total number of threads kept at reserve
for execution.

The advantages of the thread pool are :

o Using a thread pool, performance can be enhanced.


o Using a thread pool, better system stability can occur.

Concurrency Interview Questions


34) What are the main components of concurrency API?
Concurrency API can be developed using the class and interfaces of java.util.Concurrent
package. There are the following classes and interfaces in java.util.Concurrent package.

o Executor
o FarkJoinPool
o ExecutorService
o ScheduledExecutorService
o Future
o TimeUnit(Enum)
o CountDownLatch
o CyclicBarrier
o Semaphore
o ThreadFactory
o BlockingQueue
o DelayQueue
o Locks
o Phaser
35) What is the Executor interface in Concurrency API in
Java?
The Executor Interface provided by the package java.util.concurrent is the simple
interface used to execute the new task. The execute() method of Executor interface is
used to execute some given command.

36) What is BlockingQueue?


The java.util.concurrent.BlockingQueue is the subinterface of Queue that supports the
operations such as waiting for the space availability before inserting a new value or
waiting for the queue to become non-empty before retrieving an element from it.

Method Overriding and Dynamic Method Dispatch or


Java up Casting in Java
Method overriding is one of the ways in which Java supports Runtime Polymorphism. If
subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Method overriding is also referred to as runtime polymorphism because


calling method is decided by JVM during runtime.

The key benefit of overriding is the ability to define method that's specific
to a particular subclass type.

Rules for Method Overriding

1. Method name must be same for both parent and child classes.
2. Access modifier of child method must not restrictive than parent class
method.
3. Private, final and static methods cannot be overridden.
4. There must be an IS-A relationship between classes (inheritance).

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

In Java, Method Overloading is not possible by changing the return type of the method
only.

 Why method overriding is used?


- Method overriding helps in writing a generic code based on the parent class. It
provides multiple implementations of the same method and can be used to
invoke parent class overridden methods using super keyword. It defines what
behavior a class can have
 Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time. This is an important
concept because of how Java implements run-time polymorphism.
 Overriding a method is a perfect example of dynamic binding in java. Dynamic
binding or runtime polymorphism allows the JVM to decide the method's
functionality at runtime. Dynamic binding is used when a subclass overrides a
method defined in its superclass.
 In Java, method overriding occurs when a subclass (child class) has the same
method as the parent class. In other words, method overriding occurs when a
subclass provides a particular implementation of a method declared by one of its
parent classes.
 Which method cannot be overridden?
-Static Method

 Why method overriding is called dynamic polymorphism?


-method overriding is an example of run time/dynamic polymorphism
because method binding between method call and method definition happens at
run time and it depends on the object of the class (object created at runtime and
goes to the heap).

 Dynamic polymorphism is a process or mechanism in which a call to an


overridden method is to resolve at runtime rather than compile-time. It is also
known as runtime polymorphism or dynamic method dispatch. We can achieve
dynamic polymorphism by using the method overriding.
 What is the difference between polymorphism and multiple dispatch?
-Single dispatch is a type of polymorphism where only one parameter is used (the
receiver of the message - this , or self ) to determine the call. Multiple dispatch is a
type of polymorphism where in multiple parameters are used in determining which
method to call.
 What is method overriding with example?
-When we call displayInfo() using the d1 object (object of the subclass), the
method inside the subclass Dog is called. The displayInfo() method of the subclass
overrides the same method of the superclass.

 Real time example of method overriding in Java


Many of the real world habits of a parent child can be overridden in nature. For
example, a parent child can have a common behavior singing; where in the singing
behavior of a child may be different than his parent.

 What is a real time example of polymorphism?

-Real-life Illustration Polymorphism: A person at the same time can have


different characteristics. Like a man at the same time is a father, a husband, and an
employee. So the same person possesses different behavior in different situations.
This is called polymorphism.

Can we overload java main() method?


Yes, by method overloading. You can have any number of main methods in a class
by method overloading. But JVM calls main() method which receives string array
as arguments only. Let's see the simple example:

Example of Method Overriding:


class Animal
{
public void eat()
{
System.out.println("Eat all eatables");
}
}
class Dog extends Animal
{
public void eat() //eat() method overridden by Dog class.
{
System.out.println("Dog like to eat meat");
}
public static void main(String[] args)
{
Dog d = new Dog();
d.eat();
}
}

Output:
Dog like to eat meat

As you can see here Dog class gives it own implementation of eat() method. For method
overriding, the method must have same name and same type signature in both parent and
child class.

NOTE: Static methods cannot be overridden because, a static method is bounded with
class where as instance method is bounded with object.

Difference between Overloading and Overriding

Method overloading and Method overriding seems to be similar concepts


but they are not. some differences between both of them:

Method Overloading Method Overriding

Parameter must be Both name and parameter must be same.


different and name must
Method Overloading Method Overriding

be same.

Compile time
Runtime polymorphism.
polymorphism.

Increase readability of
Increase reusability of code.
code.

Access specifier can be Access specifier cannot be more restrictive than


changed. original method(can be less restrictive).

It is Compiled Time
It is Run Time Polymorphism.
Polymorphism.

It is performed within a It is performed between two classes using


class inheritance relation.

It is performed between
two classes using It requires always inheritance.
inheritance relation.

It should have methods with same name and


It should have methods
signature.
with the same name but a
Method Overloading Method Overriding

different signature.

It can not have the same


It should always have the same return type.
return type.

It can be performed using


It can not be performed using the static method
the static method

It uses static binding It uses the dynamic binding.

Access modifiers and Non-


Access modifiers and Non-access modifiers can
access modifiers can be
not be changed.
changed.

It is code refinement
It is a code replacement technique.
technique.

No keywords are used Virtual keyword is used in the base class and
while defining the method. overrides keyword is used in the derived class.

Private, static, final


Private, static, final methods can not be
methods can be
overloaded
overloaded
Method Overloading Method Overriding

No restriction is Throws
Restriction in only checked exception.
Clause.

It is also known as
Compile time
polymorphism or static
It is also known as Run time polymorphism or
polymorphism or early
Dynamic polymorphism or Late binding
binding

Example

Example:

class
OverloadingDemo{
class Demo2{
static int add1(int
x,int y){return void a()
x+y;}
{System.out.println("A");}}
static int add1(int
x,int y,int class b extends c
z){return x+y+z;}
{void a(){System.out.println("B");}
}
Que. Can we Override static method? Explain with reasons?

No, we cannot override static method. Because static method is bound to


class whereas method overriding is associated with object i.e at runtime.

Dynamic method dispatch is a mechanism by which a call to an overridden


method is resolved at runtime. This is how java implements runtime
polymorphism. When an overridden method is called by a reference, java
determines which version of that method to execute based on the type of
object it refer to. In simple words the type of object which it referred
determines which version of overridden method will be called.

Upcasting in Java

When Parent class reference variable refers to Child class object, it is


known as Upcasting. In Java this can be done and is helpful in scenarios
where multiple child classes extends one parent class. In those cases we can
create a parent class reference and assign child class objects to it.

class Game
{
public void type()
{
System.out.println("Indoor & outdoor");
}
}

Class Cricket extends Game


{
public void type()
{
System.out.println("outdoor game");
}

public static void main(String[] args)


{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm = ck; //gm refers to Cricket object
gm.type(); //calls Cricket's version of type
}
}
Output:

Indoor & outdoor


Outdoor game
Outdoor game

This is because of the statement, gm = ck;. Now gm.type() will call


the Cricket class version of type() method. Because here gm refers to the cricket
object.

this keyword
In Java, this is a keyword which is used to refer current object of a class.
we can it to refer any member of the class. It means we can access any
instance variable and method by using this keyword.

The main purpose of using this keyword is to solve the confusion when we
have same variable name for instance and local variables.
We can use this keyword for the following purpose.

 this keyword is used to refer to current object.

 this is always a reference to the object on which method was invoked.

 this can be used to invoke current class constructor.

 this can be passed as an argument to another method.

it can be used to differentiate local and instance variables in the class.

class Demo

Double width, height, depth;

Demo (double w, double h, double d)

this.width = w;

this.height = h;

this.depth = d;

public static void main(String[] args) {

Demo d = new Demo(10,20,30);

System.out.println("width = "+d.width);

System.out.println("height = "+d.height);

System.out.println("depth = "+d.depth);

}
}

Output:

width = 10.0
height = 20.0
depth = 30.0

Here this is used to initialize member of current object. Such


as, this.width refers to the variable of the current object and width only
refers to the parameter received in the constructor i.e the argument passed
while calling the constructor.
Calling Constructor using this keyword
We can call a constructor from inside the another function by using this
keyword
Accessing Method using this keyword
This is another use of this keyword that allows to access method. We can
access method using object reference too but if we want to use implicit
object provided by Java then use this keyword.

class Demo

public void getName()

System.out.println("Welcome");

public void display()

this.getName();
}

public static void main(String[] args) {

Demo d = new Demo();

d.display();

Output:

Welcome

Return Current Object from a Method


In such scenario, where we want to return current object from a method
then we can use this to solve this problem.

class Demo
{
public void getName()
{
System.out.println("Welcome");
}

public void display()


{
this.getName();
}

public static void main(String[] args) {


Demo d = new Demo();
d.display();
}
}
Output:

Welcome

// Radio Button Example………………………………………….


import javax.swing.*;
import java.awt.event.*;
public class RadioButtonExample extends JFrame
implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}

/*
<applet code="RadioButtonExample.class" width="500"
height="500">
</applet>
*/---------------------------------------------------------------------

You might also like