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

JAVA-Notes-Unit-2_Part 1

The document covers the concepts of inheritance and polymorphism in Java, detailing various forms of inheritance such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. It explains the need for inheritance, including code reusability and extensibility, and outlines member access rules for public, private, protected, and default members. Additionally, it provides examples and syntax for implementing these concepts in Java.

Uploaded by

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

JAVA-Notes-Unit-2_Part 1

The document covers the concepts of inheritance and polymorphism in Java, detailing various forms of inheritance such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. It explains the need for inheritance, including code reusability and extensibility, and outlines member access rules for public, private, protected, and default members. Additionally, it provides examples and syntax for implementing these concepts in Java.

Uploaded by

kishore0331
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Inheritance & Polymorphism PART-1


Inheritance: Introduction, Forms of Inheritance - specialization, specification,
construction, extension, limitation, combination, Member access rules, super keyword
Polymorphism- method overriding, abstract classes, final keyword.

Inheritance
Inheritance is an important pillar of OOP (Object-Oriented Programming). It is
the mechanism in Java by which one class is allowed to inherit the features (fields
and methods) of another class.

In Java, Inheritance means creating new classes based on existing ones. A class
that inherits from another class can reuse the methods and fields of that class. In
addition, you can add new fields and methods to your current class as well.

The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as superclass
(base class, parent class).

It represents a parent-child relationship between two classes. This parent-


child relationship is also known as an IS-A relationship.

Need of Inheritance

 Code Reusability: The basic need of an inheritance is to reuse the features. If


you have defined some functionality once, by using the inheritance you can
easily use them in other classes and packages.
 Extensibility: The inheritance helps to extend the functionalities of a class. If
you have a base class with some functionalities, you can extend them by using
the inheritance in the derived class.
 Implementation of Method Overriding: Inheritance is required to achieve one
of the concepts of Polymorphism which is Method overriding.
 Achieving Abstraction: Another concept of OOPs that is abstraction also needs
inheritance.

B.Tech (CSE-DS)-II-II Sem Page 1


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Syntax to implement inheritance

class Super
{
.....
.....
}
class Sub extends Super
{
.....
.....
}

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

Types of Inheritance in Java


Five different types of inheritances are possible in Object-Oriented Programming.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

B.Tech (CSE-DS)-II-II Sem Page 2


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

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

When one class inherits multiple classes, it is known as multiple inheritance. For
Example: there are three classes A, B, and C. The C class inherits A and B classes. If
A and B classes have the same method and we call it from child class object, there will
be ambiguity to call the method of A or B class.

1. Single Inheritance:
In single inheritance, a sub-class is derived from only one super class. It
inherits the properties and behavior of a single-parent class. Sometimes, it is also
known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a
child class. The class ‘B’ inherits all the properties of the class ‘A’.

B.Tech (CSE-DS)-II-II Sem Page 3


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Program on Single Inheritance


// Superclass: Vehicle
class Vehicle
{
String brand;
int speed;

public Vehicle(String brand, int speed)


{
this.brand = brand;
this.speed = speed;
}
public void displayInfo()
{
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}

// Subclass: Car
class Car extends Vehicle
{
int numberOfDoors;

public Car(String brand, int speed, int numberOfDoors)


{
super(brand, speed);
this.numberOfDoors = numberOfDoors;
}

public void displayCarInfo()


{
displayInfo();
System.out.println("Number of Doors: " + numberOfDoors);
}
}

B.Tech (CSE-DS)-II-II Sem Page 4


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

public class Single


{
public static void main(String[] args)
{
Car c = new Car("Toyota", 180, 4);
c.displayCarInfo();
}
}

2. Multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as


well as the derived class also acts as the base class for other classes. 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. In Java, a class cannot directly access
the grandparent’s members.

B.Tech (CSE-DS)-II-II Sem Page 5


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Program on MultiLevel Inheritance


// Superclass: Vehicle
class Vehicle
{
String brand;
public Vehicle(String brand)
{
this.brand = brand;
}
public void displayBrand()
{
System.out.println("Brand: " + brand);
}
}
// Subclass: Car (derived from Vehicle)
class Car extends Vehicle
{
int speed;
public Car(String brand, int speed)
{
super(brand);
this.speed = speed;
}
public void displaySpeed()
{
System.out.println("Speed: " + speed + " km/h");
}
}
// Subclass: SportsCar (derived from Car)
class SportsCar extends Car
{
boolean isTurbo;
public SportsCar(String brand, int speed, boolean isTurbo)
{
super(brand, speed);
this.isTurbo = isTurbo;
}

B.Tech (CSE-DS)-II-II Sem Page 6


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

public void displayTurbo()


{
System.out.println("Turbo: " + (isTurbo ? "Yes" : "No"));
}
}
public class MultiLevel
{
public static void main(String[] args)
{
SportsCar sc = new SportsCar("Ferrari", 350, true);
sc.displayBrand();
sc.displaySpeed();
sc.displayTurbo();
}
}

3. Hierarchical Inheritance
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.

B.Tech (CSE-DS)-II-II Sem Page 7


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Program on Hierarchical Inheritance


// Superclass: Vehicle
class Vehicle
{
String brand;
int speed;

public Vehicle(String brand, int speed)


{
this.brand = brand;
this.speed = speed;
}

public void displayInfo()


{
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}

// Subclass: Car
class Car extends Vehicle
{
int numberOfDoors;

public Car(String brand, int speed, int numberOfDoors)


{
super(brand, speed);
this.numberOfDoors = numberOfDoors;
}

public void displayCarInfo()


{
displayInfo();
System.out.println("Number of Doors: " + numberOfDoors);
}
}

B.Tech (CSE-DS)-II-II Sem Page 8


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Subclass: Truck
class Truck extends Vehicle
{
int loadCapacity;
public Truck(String brand, int speed, int loadCapacity)
{
super(brand, speed);
this.loadCapacity = loadCapacity;
}
public void displayTruckInfo()
{
displayInfo();
System.out.println("Load Capacity: " + loadCapacity + " tons");
}
}
//Main Class
public class Hierarchical
{
public static void main(String[] args)
{
Car c = new Car("Honda", 160, 4);
Truck t = new Truck("Volvo", 120, 15);

c.displayCarInfo();
t.displayTruckInfo();
}
}

B.Tech (CSE-DS)-II-II Sem Page 9


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

4. Multiple Inheritance (Through Interfaces)

In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Please note that Java
does not support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces. In the image below, Class C is derived from
interfaces A and B.

//Program to implement Multiple Inheritance


// Interface 1: Speed
interface Speed
{
void setSpeed(int speed);
void displaySpeed();
}

// Interface 2: Fuel
interface Fuel
{
void setFuelType(String fuelType);
void displayFuelType();
}

B.Tech (CSE-DS)-II-II Sem Page 10


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Concrete class: Vehicle implements both interfaces


class Vehicle implements Speed, Fuel
{
String brand;
int speed;
String fuelType;

public Vehicle(String brand)


{
this.brand = brand;
}

@Override
public void setSpeed(int speed)
{
this.speed = speed;
}

@Override
public void displaySpeed()
{
System.out.println("Speed: " + speed + " km/h");
}

@Override
public void setFuelType(String fuelType)
{
this.fuelType = fuelType;
}

@Override
public void displayFuelType()
{
System.out.println("Fuel Type: " + fuelType);
}

B.Tech (CSE-DS)-II-II Sem Page 11


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

public void displayBrand()


{
System.out.println("Brand: " + brand);
}
}
//Main class
public class Multiple
{
public static void main(String[] args)
{
Vehicle v = new Vehicle("Tesla");
v.setSpeed(200);
v.setFuelType("Electric");

v.displayBrand();
v.displaySpeed();
v.displayFuelType();
}
}

5. Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple
inheritance is also not possible with classes. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.

B.Tech (CSE-DS)-II-II Sem Page 12


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

However, it is important to note that Hybrid inheritance does not necessarily


require the use of Multiple Inheritance exclusively.

 It can be achieved through a combination of Multilevel Inheritance and


Hierarchical Inheritance with classes.

 Hierarchical and Single Inheritance with classes.

Therefore, it is indeed possible to implement Hybrid inheritance using classes


alone, without relying on multiple inheritance type.

//Program on Hybrid Inheritance


// Interface 1: Speed
interface Speed
{
void setSpeed(int speed);
void displaySpeed();
}

// Interface 2: Engine
interface Engine
{
void startEngine();
void stopEngine();
}

B.Tech (CSE-DS)-II-II Sem Page 13


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Superclass: Vehicle
class Vehicle
{
String brand;

public Vehicle(String brand)


{
this.brand = brand;
}

public void displayBrand()


{
System.out.println("Brand: " + brand);
}
}

// Subclass: Car implements both interfaces (Speed, Engine)


class Car extends Vehicle implements Speed, Engine
{
int speed;

public Car(String brand)


{
super(brand);
}

@Override
public void setSpeed(int speed)
{
this.speed = speed;
}

@Override
public void displaySpeed()
{
System.out.println("Speed: " + speed + " km/h");
}

B.Tech (CSE-DS)-II-II Sem Page 14


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

@Override
public void startEngine()
{
System.out.println("Engine started.");
}

@Override
public void stopEngine()
{
System.out.println("Engine stopped.");
}
}
//Main class
public class Hybrid
{
public static void main(String[] args)
{
Car c = new Car("BMW");
c.displayBrand();
c.setSpeed(220);
c.displaySpeed();
c.startEngine();
c.stopEngine();
}
}

B.Tech (CSE-DS)-II-II Sem Page 15


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Forms of Inheritance in Java


The following are the different forms of inheritance in java.

1. Specialization
2. Specification
3. Construction
4. Extension or Generalization
5. Limitation
6. Combination

1. Specialization
It is the most ideal form of inheritance. The subclass is a special case of the
parent class. It holds the principle of substitutability.
2. Specification
This is another commonly used form of inheritance. In this form of inheritance,
the parent class just specifies which methods should be available to the child class
but doesn't implement them. The java provides concepts like abstract and interfaces
to support this form of inheritance. It holds the principle of substitutability.
3. Construction
This is another form of inheritance where the child class may change the
behavior defined by the parent class (overriding). It does not hold the principle of
substitutability.
4. Extension or Generalization
This is another form of inheritance where the child class may add its new
properties. It holds the principle of substitutability.
5. Limitation
This is another form of inheritance where the subclass restricts the inherited
behavior. It does not hold the principle of substitutability.
6. Combination
This is another form of inheritance where the subclass inherits properties from
multiple parent classes. Java does not support multiple inheritance type.

B.Tech (CSE-DS)-II-II Sem Page 16


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Member access rules in Inheritance

1. public Members

 Superclass: public members of the superclass are accessible from any class,
including subclasses, regardless of the package.
 Subclass: A subclass can access public members of its superclass without any
restriction.

2. private Members

 Superclass: private members of the superclass cannot be accessed directly by


any other class, including subclasses. These members are hidden from the
subclass.
 Subclass: A subclass cannot access the private members of the superclass
directly. However, the subclass can still access private members via
getter/setter methods or other public/protected methods provided by the
superclass.

3. protected Members

 Superclass: protected members of the superclass are accessible within the same
package and in subclasses (even if they are in different packages).
 Subclass: A subclass can access protected members of its superclass, whether
the subclass is in the same package or in a different package.

4. default (Package-specific) Members

 Superclass: Members with default access (no modifier) are accessible only
within the same package.
 Subclass: If the subclass is in the same package, it can access these members. If
the subclass is in a different package, it cannot access these members.

B.Tech (CSE-DS)-II-II Sem Page 17


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Vehicle class with different access modifiers


class Vehicle
{
//Can be accessed from anywhere
public String brand;

//Can only be accessed within the Vehicle class


private int year;

//Can be accessed within the package and by subclasses


protected String model;

//default Can be accessed only within the same package


String color;
public Vehicle(String brand, int year, String model, String color)
{
this.brand = brand;
this.year = year;
this.model = model;
this.color = color;
}
// Public method to access the private variable
public int getYear()
{
return year;
}
// Only accessible within the Vehicle class
private void displayPrivateInfo()
{
System.out.println("Private method: Year of the vehicle is " + year);
}
//Accessible within the package and by subclasses
protected void displayModel()
{
System.out.println("Model: " + model);
}
}

B.Tech (CSE-DS)-II-II Sem Page 18


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Subclass of Vehicle
class Car extends Vehicle
{
public Car(String brand, int year, String model, String color)
{
super(brand, year, model, color);
}
// Subclass can access protected member and method
public void displayCarInfo()
{
System.out.println("Brand: " + brand);
System.out.println("Model (from subclass): " + model); // access protected member
displayModel(); // Can call protected method
}
}

// Main class
public class Access
{
public static void main(String[] args)
{
Vehicle v = new Vehicle("Toyota", 2020, "Corolla", "Red");
// Public member can be accessed directly
System.out.println("Brand: " + v.brand);
// Cannot access private member directly, so using the public getter method
System.out.println("Year: " + v.getYear());
// Cannot access private method directly
//v.displayPrivateInfo(); // This would cause a compile-time error
// Accessing default/package-private member within the same package
System.out.println("Color: " + v.color);
// Subclass can access protected members and methods
Car c = new Car("Honda", 2021, "Civic", "Blue");
c.displayCarInfo();
}
}

B.Tech (CSE-DS)-II-II Sem Page 19


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

super keyword

The super keyword in Java is used as a reference variable to access objects


from parent classes. It allows access to parent class constructors, members, and
methods in the derived class. The keyword plays a crucial role in inheritance and
polymorphism concepts.

Use of super keyword in Java

1. super in Variables: Used to access a variables from the superclass, especially if the
subclass has a field with the same name.
2. super in Methods: Used to call a method from the superclass, especially when the
method is overridden in the subclass.
3. Super() in Constructors: Used to invoke a constructor of the superclass. If the
superclass doesn't have a no-argument constructor, you need to call one of its
constructors explicitly using super().

B.Tech (CSE-DS)-II-II Sem Page 20


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Program on Super Keyword


// Superclass
class Vehicle
{
String brand;
int year;
// Constructor of the superclass
Vehicle(String brand, int year)
{
this.brand = brand;
this.year = year;
}
// Method in the superclass
void displayInfo()
{
System.out.println("Brand: " + brand);
}
}
// Subclass
class Car extends Vehicle
{
int doors;
// Constructor of the subclass
Car(String brand, int year, int doors)
{
// Using super to call the superclass constructor
super(brand, year);
this.doors = doors;
}
// Method in the subclass
void displayCarInfo()
{
// Using super to call the superclass method
super.displayInfo();
System.out.println("Year: " + super.year);
System.out.println("Doors: " + doors);
}
}

B.Tech (CSE-DS)-II-II Sem Page 21


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Main class
public class SuperKey
{
public static void main(String[] args)
{
Car c = new Car("Toyota", 2020, 4);
c.displayCarInfo();
}
}

Restrictions on super:

 super can only be used to access members of the immediate superclass.


 super cannot be used to access private members of the superclass directly, as
those are not visible outside the class.
 super cannot be used to call static methods or static variables of the superclass.

Polymorphism
The term "polymorphism" means "many forms". In object-oriented
programming, polymorphism is useful when you want to create multiple forms with
the same name of a single entity.

Polymorphism in Java is mainly of 2 types as mentioned below:

1. Method Overloading
2. Method Overriding

B.Tech (CSE-DS)-II-II Sem Page 22


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

1. Method Overloading: Also, known as compile-time polymorphism, is the


concept of Polymorphism where more than one method share the same name with
different signature (Parameters) in a class. The return type of these methods can or
cannot be same.

2. Method Overriding: Also, known as run-time polymorphism, is the concept of


Polymorphism where method in the child class has the same name, return-type
and parameters as in parent class. The child class provides the implementation in
the method already written in the parent class.

//Program on method overloading & overriding


// Parent Class
class Parent
{
// Method Defined
public void m1()
{
System.out.println("Parent Method m1 executed");
}
// Method Overloading
public void m1(int a)
{
System.out.println("Parent Method m1 with parameter: " + a);
}
}

// Child Class
class Child extends Parent
{
// Method Overriding
public void m1(int a)
{
System.out.println("Child Method m1 with parameter: " + a);
}
}

B.Tech (CSE-DS)-II-II Sem Page 23


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Main Method
class Poly
{
public static void main(String args[])
{
Parent p = new Parent();
p.m1();
p.m1(5);
Child c = new Child();
c.m1(4);
}
}

//Program on method overriding


// Superclass vehicle
class Vehicle
{
String brand;
public Vehicle(String brand)
{
this.brand = brand;
}

// Method that will be overridden by subclasses


public void hornSound()
{
System.out.println(brand + " horn sound: Beep Beep!");
}
}

B.Tech (CSE-DS)-II-II Sem Page 24


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Subclass of Vehicle
class Car extends Vehicle
{
public Car(String brand)
{
super(brand);
}
// Overriding the hornSound method in the Car class
public void hornSound()
{
System.out.println(super.brand + " horn sound: Honk Honk!");
}
}
//Main class
public class Override
{
public static void main(String[] args)
{
Vehicle v = new Vehicle("Toyota");
v.hornSound();
Car c = new Car("Honda");
c.hornSound();
}
}

B.Tech (CSE-DS)-II-II Sem Page 25


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

abstract classes
Abstraction in Java
Abstraction is a process of showing the essential features and hiding their
implementation details to the user.

There are two ways to achieve abstraction in Java:

1. Using Abstract Classes (0 to 100%)


2. Using Interfaces (100%)

1. Abstract Class

An abstract class in Java acts as a partially implemented class that itself cannot be
instantiated. It exists only for subclassing purposes, and provides a template for its
subcategories to follow. Abstract classes can have implementations with abstract
methods. Abstract methods are declared to have no body, leaving their implementation
to subclasses.

abstract class ClassName


{
// Abstract method (no implementation)
abstract void abstractMethod();

// Concrete method (with implementation)


void concreteMethod()
{
System.out.println("This is a concrete method");
}
}

Points to Remember

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.
o We can’t use final and abstract for a class at a time.

B.Tech (CSE-DS)-II-II Sem Page 26


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Program to implement abstract classes


// Abstract class: Vehicle
abstract class Vehicle
{
String brand;
int speed;
// Constructor
public Vehicle(String brand, int speed)
{
this.brand = brand;
this.speed = speed;
}

// Abstract method: This method must be implemented by subclasses


abstract void startEngine();

// Regular method: Subclasses can inherit this directly


public void displayInfo()
{
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}

// Subclass: Car
class Car extends Vehicle
{
public Car(String brand, int speed)
{
super(brand, speed);
}
// Implementing the abstract method startEngine
void startEngine()
{
System.out.println("Car engine started.");
}
}

B.Tech (CSE-DS)-II-II Sem Page 27


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Subclass: Truck
class Truck extends Vehicle
{
int loadCapacity; // in tons
public Truck(String brand, int speed, int loadCapacity)
{
super(brand, speed);
this.loadCapacity = loadCapacity;
}
// Implementing the abstract method startEngine
void startEngine()
{
System.out.println("Truck engine started.");
}
// Method specific to Truck class
public void displayLoadCapacity()
{
System.out.println("Load Capacity: " + loadCapacity + " tons");
}
}
//Main class
public class Abstraction
{
public static void main(String[] args)
{
// Creating objects of Car and Truck
Car c = new Car("Toyota", 180);
Truck t = new Truck("Volvo", 100, 10);
// Calling methods
c.startEngine();
c.displayInfo();
t.startEngine();
t.displayInfo();
t.displayLoadCapacity();
}
}

B.Tech (CSE-DS)-II-II Sem Page 28


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

final keyword

The final keyword in Java is used to define constants, prevent method


overriding, and prevent inheritance. It can be applied to variables, methods, and
classes, each serving a different purpose.

Uses of the final Keyword in Java:

1. Final Variables (Constants): When you declare a variable as final, its value
cannot be changed once it is assigned. Essentially, the variable becomes a
constant.

2. Final Methods: A final method cannot be overridden by subclasses. This is


useful when you want to ensure that a particular method’s behavior remains
unchanged.

3. Final Classes: A final class cannot be subclassed (inherited). This is useful


when you want to prevent a class from being extended.

4. Final Parameters: You can also use the final keyword on method parameters,
which makes the parameters immutable within the method.

B.Tech (CSE-DS)-II-II Sem Page 29


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//program on final keyword


// Final class: Cannot be subclassed
final class Vehicle
{
final String brand; //Cannot be changed once assigned
final int year; //Cannot be changed once assigned

// Constructor
Vehicle(String brand, int year)
{
this.brand = brand;
this.year = year;
}
// Method with final parameter
public void setVehicleType(final String vehicleType)
{
// Uncommenting the following line would cause a compilation error
// vehicleType = "Truck"; // Error: cannot assign a value to final variable
System.out.println("Vehicle type is: " + vehicleType);
}
// Final method: Cannot be overridden by subclasses
final void displayInfo()
{
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

// Uncommenting the following line will cause a compile-time error because Vehicle
is final
// class Car extends Vehicle
// {

// }

B.Tech (CSE-DS)-II-II Sem Page 30


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Main class
public class FinalKey
{
public static void main(String[] args)
{
Vehicle v = new Vehicle("Toyota", 2020);
// Passing a String parameter to the setVehicleType method
v.setVehicleType("Car");
// The final variable brand cannot be reassigned
// v.brand = "Honda"; // This would cause a compile-time error
v.displayInfo(); // Calling the final method
}
}

B.Tech (CSE-DS)-II-II Sem Page 31

You might also like