Java Control Statements Overview
Java Control Statements Overview
UNIT-II
Classes and Objects: Basic concepts of OOPS, Classes and Objects, Modifiers, Passing
arguments, Constructors, Overloaded Constructors, Overloaded Operators, Static Class Members,
Garbage Collection.
Control Statements:
Java compiler executes the code in the program from top to bottom. The statements in the code are
executed according to their order in which they appear in the program. However, Java provides
statements that can be used to control the flow of Java code. Those statements are called control
flow statements. It is a fundamental features of Programming including Java programming
language.
JAVA (UGCA-1932)
UNIT-II
if-else statement:
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
the else block. The else block is executed if the condition of the if-block is false.
JAVA (UGCA-1932)
UNIT-II
Syntax:
if(condition) {
statement 1; //executes when the condition is true
}
else{
statement 2; //executes when the condition is false
}
Example:
public class Student {
pubic static void main(String args[])
{
int age = 15;
if(age >=18)
{
[Link](“Eligible for vote!”);
}
Else{
[Link](“Not Eligible for vote!”);
}
}
}
Output:
Note Eligible for vote!
Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
JAVA (UGCA-1932)
UNIT-II
}
else {
statement 2; } //executes when all the conditions are false
Examkple:
public class Student {
pubic static void main(String args[])
{
int age = 22;
if(age >=21)
{
[Link](“Eligible for abroad employment & Voting in India!”);
}
else-if(age>=18){
[Link](“Eligible for vote in India only!”);
}
Else{
[Link](“He/She is minor Studen!”);
}
}
}
OUTPUT:
Nested if-statement:
In nested if-statements, the if statement can contain an if or if-else statement inside another if or
else-if statement.
Syntax
if(condition 1) {
if(condition 2) { //nesting
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
JAVA (UGCA-1932)
UNIT-II
passed as a parameter of the switch statement. The switch statement is easier to use instead of if-
else-if statements. It also enhances the readability of the program.
Syntax:
switch (expression/condition){
case value1:
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
break;
default:
default statement;
}
Example:
class Main {
public static void main(String[] args) {
int number = 3;
String day;
JAVA (UGCA-1932)
UNIT-II
switch (number) {
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
// match the value of the weekdays
case 3:
day= "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
case 7:
day = "Sunday";
break;
default:
day = "Invalid Number!";
break;
}
[Link]("Day: " + day);
}
}
OUTPUT
Conditional Operator:
Conditional operators in Java are essential for creating logical expressions that give Boolean
results. They control the flow of execution in a Java program, enabling different actions or
statements based on specific conditions.
JAVA (UGCA-1932)
UNIT-II
By using conditional operators, developers can create dynamic decision-making structures. It also
helps improve the functionality and adaptability of their Java applications.
1. Conditional AND
The conditional AND is a binary operator denoted by the symbol “&&” which combines boolean
expressions and returns true only if both expressions are true. The result will return false if any
one expression is false.
Syntax:
condition1 && condition2
//It evaluates both condition 1 and condition 2.
Example:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 10;
boolean condition1 = (x > 0); // true
boolean condition2 = (y > 5); // true
boolean result = condition1 && condition2;
[Link](result); // Output: true
}
}
Output:
True
2. Conditional OR
The conditional OR operator is denoted by the symbol “||”. It combines two Boolean expressions,
which return true if one of them expressions is true. The result will be false if the expressions are
false.
Syntax:
condition1 || condition2
//It evaluates both condition1 and condition 2.
Example:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 10;
boolean condition1 = (x > 0); // true
JAVA (UGCA-1932)
UNIT-II
3. Ternary Operator:
The meaning of ternary is composed of three parts. The ternary Operator (?:) consists of three
operands. It’s a one-liner replacement for the if-else statements and is used a lot in Java
programming. It takes less space and helps to write the if-else statements in the shortest way.
Syntax:
variable = Expression1 ? Expression2: Expression3
Example:
class Ternary {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, max;
Looping Statements:
JAVA (UGCA-1932)
UNIT-II
Looping is a feature that facilitates the execution of a set of instructions repeatedly until a certain
condition is false. Loops are also known as Iterating statements or Looping constructs in Java.
In simple, computer programming loops are used to repeat a block of code. For example, if you
want to show a message 100 times, then rather than typing the same code 100 times, you can use
a loop.
In above syntax:
The initialization, declares a variable and executes only once.
The condition is evaluated. If the condition is true, the body of the for loop is executed.
The increment/decrement updates the initialized value.
The condition is evaluated again. The process continues until the condition is false.
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
[Link]("SHAHID is learning Java!");
}
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
[Link](i);
}
}
}
OUTPUT
Syntax:
while (condition)
{
loop statements...
}
JAVA (UGCA-1932)
UNIT-II
Example:
class while_loop {
public static void main (String[] args) {
int i=1;
while (i<5)
{
[Link]("Shahid is learning Java!");
i++;
}
}}
OUTPUT
Syntax:
do
{
statements..
}
while (condition);
Example:
class do_while_loop {
public static void main (String[] args) {
int i=1;
do
{
[Link]("You are learning do-while loop.");
i++;
}while(i<5);
}
}
JAVA (UGCA-1932)
UNIT-II
OUTPUT
Nested Loop:
A nested loop means a loop statement inside another loop statement. There are different
combinations of loop using for loop, while loop, and do-while loop.
1. Break statement.
2. Continue statement.
3. Return Statement
Break Statement:
The break statement is used to terminate the execution of a loop or switch statement. When a break
statement is encountered inside a loop or switch statement it immediately exits the loop or switch
control flow.
Example:
class break_statement {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6) //stops iteration when 6 is encountered
break;
[Link](i);
}
}
}
OUTPUT
Continue Statement:
The continue statement is used to skip the current iterative value or statement of result and proceed
to the next iteration. It means that, it skips any code following the continue statement within the
loop and jumps to the next iteration.
JAVA (UGCA-1932)
UNIT-II
Example:
class Continue_statement{
public static void main(String[] args)
{
for (int i = 1; i <=10; i++) {
if (i == 5){
[Link]();
continue; // to skip the current iterative value 5
}
[Link](i);
}
}
}
OUTPUT
Example:
class ReturnExample {
public static int calculateSum(int num1, int num2)
{
int sum = num1 + num2;
// Return the calculated sum
return sum;
}
JAVA (UGCA-1932)
UNIT-II
Classes:
A class in Object-oriented Programming (OOP) is a blueprint or template that defines the attributes
(data) and methods (functions) that is accessed using object. It encapsulates the data and methods
to manipulate using objects. Classes are fundamental element of OOP as they enable the creation
of modular and reusable code.
JAVA (UGCA-1932)
UNIT-II
Object:
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities.
Objects are the instances of a class that are created to use the attributes and methods of a class.
When a class is defined, no memory is allocated until an object of that class is created.
An object consists of:
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object with other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
For Example: a student named Shahid is a Real-World entity which has his behavior like walking,
speaking, eating, etc., in programming terms it's an Object.
Syntax:
//object of a class
Test obj = new Test();
Example:
public class Object_example {
int roll = 295;
String name = "Shahid";
OUTPUT
Class vs Object:
Object Class
Class is a blueprint or template from
Object is an instance of a class.
which objects are created.
The object is a real-world entity such as a pen,
Class is a group of similar objects.
laptop, mobile, bed, keyboard, mouse, chair, etc.
The object is a physical entity. Class is a logical entity.
JAVA (UGCA-1932)
UNIT-II
An object is created through a new keyword mainly Class is declared using class
e.g. Student s1=new Student(); keyword e.g. class Student{}
An object is created many times as per
Class is declared once.
requirement.
Class doesn't allocate memory when it is
Object allocates memory when it is created.
created.
There are many ways to create objects in Java such
There is only one way to define a
as new keyword, newInstance() method, clone()
class in java using the class keyword.
method, factory method, and deserialization.
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 the 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.
JAVA (UGCA-1932)
UNIT-II
Private:
The private access modifier is specified using the keyword private. The methods or data members
declared as private are accessible only within the class in which they are declared. It means, When
variables and methods are declared private, they cannot be accessed outside of the class.
Example:
class Data {
// private variable
private String name;
}
In the above example, we have declared a private variable named name. When we run the program,
we will get the following error:
JAVA (UGCA-1932)
UNIT-II
Default:
When no access modifier is specified for a class, method, or data member It is said to be having
the default access modifier by default. The data members, classes, or methods that are not declared
using any access modifiers or default access modifiers are accessible only within the same
package.
Example1: (new package)
package p1;
[Link]();
}
JAVA (UGCA-1932)
UNIT-II
}
OUTPUT
Protected:
The protected access modifier is specified using the keyword protected. The methods or data
members declared as protected are accessible within the same package and outside of the package
using the concept of inheritance only. The protected access modifier can be applied to the data
member, method and constructor but it can’t be applied on the class.
Example:
In this example, will create two packages pck1 and pck2. And we will try to access the methods
from one package to another package.
Package1:
//save by .java extension
package pck1;
public class A{
protected void msg()
{
[Link]("Hi, You learning Protected Modifier.");
}
}
Package 2:
//save by .java extension
package pck2;
import pck.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
JAVA (UGCA-1932)
UNIT-II
OUTPUT
Public:
The public access modifier is specified using the keyword public. The public access modifier has
the global scope among all other access modifiers. Classes, methods, or data members that are
declared as public are accessible from everywhere in the program. There is no restriction on the
scope of public data members.
Example:
Package 1;
//save by .java extension
package pck1;
public class A{
public void msg()
{
[Link]("Hi, You learning Public Modifier.");
}
}
Package 2:
//save by .java extension
package pck2;
import pck.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
JAVA (UGCA-1932)
UNIT-II
OUTPUT
Java Constructors:
Java constructor is a technique that is used to construct something in our Java programs. A
constructor in Java is a special method that is used to initialize objects. The constructor is called
automatically when an object of a class is created.
Example:
class OOPs {
OOPs() // Constructor
{
super();
[Link]("Constructor Called");
}
public static void main(String[] args)
{
OOPs obj = new OOPs();//constructor will call automatically
} }
OUTPUT
JAVA (UGCA-1932)
UNIT-II
Default Constructor:
If we don’t provide a constructor, then Java provides a default constructor implementation for us
to use. The default constructor is always without argument and provided by Java compiler only
when there is no existing constructor defined.
Let’s look at a simple program where a default constructor is being used since we will not explicitly
define a constructor.
class Main {
int a;
boolean b;
public static void main(String[] args) {
Main obj = new Main(); // calls default constructor
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
OUTPUT
No-Arg Constructor:
Similar to methods, a Java constructor may or may not have any parameters (arguments). If a
constructor does not accept any parameters, it is known as a no-argument constructor.
Example:
class Main {
// constructor with no parameter
Main () {
[Link]("Constructor is called");
JAVA (UGCA-1932)
UNIT-II
Parameterized Constructor:
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructors with parameters).
Example:
class Main {
// constructor accepting single value
Main(String lang) {
[Link](lang + " Programming Language");
}
Constructor vs Methods:
Constructor Methods
A constructor is used to initialize the state A method is used to expose the behavior
of an object. of an object.
A constructor must not have a return type. A method must have a return type.
The constructor name must be the same as The method name may or may not be the
the class name. same as the class name.
Here, ‘MyClass’ contains multiple constructors. Each constructor has a different parameter list.
The constructors can then perform specific initialization tasks based on the parameters they
receive.
//2 constructor
Student(String name)
{
[Link]("I am a Student. My name is "+name);
}
//3 constructor
Student(String name, int roll)
{
[Link]("I am a student. My name is "+name+" and roll is "+roll);
}
OUTPUT
Static Members:
In Java, static members are those which belongs to the class and you can access these members
without instantiating the class. The static keyword can be used with methods, fields, classes, and
blocks.
Static variables, Static Initialization Block, and Static Methods; these all are static components or
static members of a class. These static members are stored inside the Class Memory. To access
static members, you need not to create objects. Directly you can access them with the class name.
Static Methods: You can create a static method by using the keyword static. Static methods can
access only static field methods. To access static methods there is no need to instantiate the class,
you can do it by just using the class name.
Example:
public class MyClass {
//static member
public static void sample(){
[Link]("Hello SHAHID");
}
public static void main(String args[]){
//static member
[Link]();//static method
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II
Static Blocks: These are a block of code with a static keyword. In general, these are used to
initialize the static members. JVM (Java Virtual Machine) executes static blocks before the main
method at the time of class loading.
Example:
public class MyClass {
//static block
static{
[Link]("Hello I am from static block");
}
public static void main(String args[]){
[Link]("I am inside main method");
}
}
OUTPUT
Static Fields: You can create a static field by using the keyword static. The static fields have the
same value in all the instances of the class. These are created and initialized when the class is
loaded for the first time. Just like static methods you can access static fields using the class name
(without instantiation).
Example:
public class MyClass {
//stati Fields
public static String name = "SHAHID";
public static int roll = 295;
public static void main(String args[]){
[Link]("My name is "+[Link]);
[Link]("My Roll no. is "+[Link]);
}
}
JAVA (UGCA-1932)
UNIT-II
OUTPUT
There are many ways to make an object eligible for garbage collection:
1. Nullifying the reference variable
Example:
Employee e = new Employee();
e = null;
3. By anonymous Object
Example:
new Employee();
JAVA (UGCA-1932)
UNIT-II
We can also request JVM to run a garbage collector using various methods:
gc() method: The gc() method is used to invoke the garbage collector to perform cleanup
processing.
Syntax:
public static void gc()
{ }
finalize() method: The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in the Object class
as:
OUTPUT
Car(String model) {
[Link] = model;
}
void printModel() {
[Link]("Car model: " + model);
}
}
Example 2:
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
boolean equalTo(ObjectPassDemo o)
{
// notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}
}
public class ObjectPassing {
public static void main(String args[])
{ // Creating object of above class inside main()
ObjectPassDemo obj1 = new ObjectPassDemo(10, 20);
ObjectPassDemo obj2 = new ObjectPassDemo(10, 20);
ObjectPassDemo obj3 = new ObjectPassDemo(-1, -1);
// Checking whether object is equal as custom values
OUTPUT
int a = 10;
int b = 20;
int c = a + b;
[Link](c); // 30
}
}
OUTPUT
30
Example 2:
Note:
In The First Example + Operator Add Two Integer values but in the Second it Add Two String.
This is called Operator Overloading. In the Above Example + operator is overloaded as it performs
different actions depending on the parameters passed.
Super Class/Parent Class: The class whose features are inherited is known as a superclass (or a
base class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass (or a derived
class, extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.
Single Inheritance:
Single inheritance refers to the inheritance where a class inherits properties and behaviors from
only one parent class. It inherits the properties and behavior of a single-parent class. Sometimes,
it is also known as simple inheritance.
JAVA (UGCA-1932)
UNIT-II
Example:
// Parent class
class One {
public void Shahid()//name of coder
{
[Link]("I am from parent class of Single Inheritance.");
}
}
//child class
class Two extends One {
public void harsh() //name of coder's friend
{
[Link]("I am from child class fro Single Inheritance.");
}
}
public class Main {
public static void main(String[] args)
{
Two obj = new Two();
[Link]();
[Link]();
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II
Multilevel Inheritance:
Multilevel inheritance involves a chain of inheritance where a derived class serves as a base class
for another class. In simple we can say that the last class inherits its previous class and that class
also inherits its previous class and so on.
In the below image, class A serves as a base class for the derived class B, which in turn serves as
a base class for the derived class C.
Syntax:
class Grandparent {
// Grandparent class members
}
class Parent extends Grandparent {
// Parent class inherits from Grandparent
}
class Child extends Parent {
// Child class inherits from Parent (and indirectly from Grandparent)
}
JAVA (UGCA-1932)
UNIT-II
Example:
// Parent class
class Grand_Parent {
public void Shahid()//name of coder
{
[Link]("I am from Grand_parent class of Multi-leve Inheritance.");
}
}
//child class
class Parent extends Grand_Parent {
public void Shahid2() {
[Link]("I am from Parent class of Multi-level Inheritance.");
}
}
class Child extends Parent {
public void Shahid3() {
[Link]("I am from child class of Multi-level Inheritance.");
}
}
public class Main {
public static void main(String[] args)
{
Child obj = new Child();
[Link]();
obj.Shahid2();
obj.Shahid3();
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II
Hierarchical Inheritance:
Hierarchical inheritance involves one base class being inherited by multiple derived classes. In
Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived classes B, C, and D.
Example:
class A {//superclass or Base class for all the classes
public void Shahid()//name of coder
{
[Link]("I am Base class in Hierarchical Inheritance.");
}
}
//child class
class B extends A {
public void Shahid2() {
[Link]("I am class B inheriting A.");
}
}
class C extends A {
public void Shahid3() {
[Link]("I am class C inheriting A.");
}
}
class D extends A {
public void Shahid4() {
[Link]("I am class D inheriting A.");
JAVA (UGCA-1932)
UNIT-II
}
}
public class Main {
public static void main(String[] args)
{
B obj = new B();
[Link]();
obj.Shahid2();
C obj2 = new C();
[Link]();
obj2.Shahid3();
D obj3 = new D();
[Link]();
obj3.Shahid4();
}
}
OUTPUT
Syntax:
interface InterfaceA {
void methodA();
}
interface InterfaceB {
void methodB();
}
Example:
interface A {//interface1
public void Shahid();//name of coder
}
interface B {//interface2
public void Shahid2() ;
}
JAVA (UGCA-1932)
UNIT-II
class C implements A, B {
public void Shahid() {
[Link]("Method1 of interface1: \nI am class C utilizing interface A And B.");
}
public void Shahid2(){
[Link]("Method2 of interface2: \nI am class C utilizing interface A And B");
}
}
public class Main {
public static void main(String[] args)
{
C obj = new C();
[Link]();
obj.Shahid2();
}
}
OUTPUT
Hybrid Inheritance:
Hybrid inheritance combines different types of inheritance within a single class. It is a mix of two
or more of the above types of inheritance. Java does not support multiple inheritance of classes,
we can achieve hybrid inheritance only through Interfaces.
JAVA (UGCA-1932)
UNIT-II
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
[Link]("Child's show()");
}
}
// Driver class
Public class Main {
public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's show is called
Parent obj1 = new Parent();
[Link]();
Example2:
class Animal {
void sound() {
[Link]("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("The dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create an Animal object
Animal myDog = new Dog(); // Create a Dog object
Animal myCat = new Cat(); // Create a Cat object
super is used to call a superclass method: A subclass can call a method defined in its
parent class using the super keyword. This is useful when the subclass wants to call the
parent class’s method.
super is used to access a superclass field: A subclass can access a field defined in its
parent class using the super keyword. This is useful when the subclass wants to access the
parent class’s field.
Overall, the super keyword is a powerful tool for sub-classing in Java, allowing subclasses to
inherit the defined functionality of their parent classes.
Example:
// superclass Person
class Person {
Person()
{
[Link]("I am from Constructor");
}
}
JAVA (UGCA-1932)
UNIT-II
Polymorphism in Java:
The word polymorphism means having many forms. In simple words, we can define Java
Polymorphism as the ability of a message to be displayed in more than one form.
Real-life Illustration of Polymorphism in Java: A person can have different characteristics at the
same time. Like a man at the same time is a father, a husband, and an employee. So the same
person possesses different behaviors in different situations. This is called polymorphism.
return a + b;
return a + b + c;
return a + b;
}
OUTPUT
Example:
// Class 1
class Parent {
// Method of parent class
void Print()
{
[Link]("I am from parent class");
}
}
// Class 2
class subclass1 extends Parent {
// Method
void Print() { [Link]("I am from subclass1"); }
}
// Class 3
class subclass2 extends Parent {
// Method
void Print()
{ [Link]("I am fromsubclass2"); }
}
public class Main {
public static void main(String[] args)
{
Parent a;
a = new Parent();
[Link]();
a = new subclass1();
[Link]();
a = new subclass2();
[Link]();
}
}
OUTPUT
JAVA (UGCA-1932)
UNIT-II
Abstract Classes:
Java abstract class is a class that cannot be initiated by itself means an instance of an abstract class
cannot be created, it needs to be sub classed by another class to use its properties.
In Java, abstract class is declared with the abstract keyword. An abstract is a Java modifier
applicable for classes and methods in Java but not for Variables.
Syntax:
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
Example:
abstract class Bird {
// Abstract method for flying
public abstract void fly();
// Abstract method for eating
public abstract void eat();
//concrete method
public void sleep() { [Link]("Bird is sleeping"); }
}
class Sparrow extends Bird {
@Override
public void fly() {
[Link]("Sparrow is flying");
}
@Override
public void eat() {
[Link]("Sparrow is eating seeds");
}
}
public class Main {
public static void main(String[] args) {
Sparrow obj = new Sparrow();
[Link](); // Output: Sparrow is flying
[Link](); // Output: Sparrow is eating seeds
[Link](); // Output: Bird is sleeping (inherited from Bird class)
}
}
JAVA (UGCA-1932)
UNIT-II
Final Class:
A final class in Java is a concept of object-oriented programming where a class is declared using
the "final" keyword. This type of class cannot be extended or inherited by other classes (meaning
that no subclass can be created from it.) making it inflexible.
If a class is complete in nature then we can make it a final class which tells us that it can’t be an
abstract class. If in case anyone tries to inherit the final class to any subclass, the compiler will
throw an error.
Final keyword:
In Java, the "final" keyword is used to indicate that a variable, method, or class can only be
assigned a value once and cannot be changed thereafter. The final keyword is used to limit access
and modification by the user. It can be used in any context such as final variable, final class, or
final method.
Syntax:
final class className
{
// Body of class
}
Example:
final class finalclass
{
void method()
{
[Link]("this is final class");
}
}
class childClass extends finalclass
{
void method()
{
JAVA (UGCA-1932)
UNIT-II
So from the above code output, we can clearly see that it will throw a compilation error because
the class is declared as final. This proves that we cannot inherit from the final class in Java.