10.final Keyword, Method Overriding, Abstraction

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

The final keyword in java is used to restrict the user.

The java final


keyword can be used in many context.
Final can be:
1.variable
2.method
3.Class

The final keyword can be applied with the variables, a final


variable that have no value is called blank final variable or
uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be
initialized in the static block only.
1) Java final variable
If you make any variable as final, you cannot change
the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to
change the value of this variable, but It can't be changed
because final variable once assigned a value can never be
changed
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run(); Output:Compile Time Error
}
}//end of class
2) Java final method
If you make any method as final, you cannot override it.

Example of final method Output:Compile Time Error


class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
} }
3) Java final class
If you make any class as final, you cannot extend it.

Example of final class Output:Compile Time Error


final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with
100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
• What is blank or uninitialized final variable?

• A final variable that is not initialized at the time of


declaration is known as blank final variable.

• If you want to create a variable that is initialized at the


time of creating object and once initialized may not be
changed, it is useful. For example PAN CARD number of
an employee.

• It can be initialized only in constructor.

• Example of blank final variable


• class Student{
• int id;
• String name;
• final String PAN_CARD_NUMBER;
• ...
• }
Can we initialize blank final variable?
Yes, but only in constructor. For example:

class Bike10{
final int speedlimit;//blank final variable
Output: 70
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[]){


new Bike10();
}
}
Static blank final variable
A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can
be initialized only in static block.

Example of static blank final variable


class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
What is final parameter?
If you declare any parameter as final, you cannot change the
value of it.
Output: Compile Time Error
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Can we declare a constructor final?

• No, because constructor is never inherited.


•Polymorphism
in
java
Polymorphism
The word polymorphism is a combination of two words i.e. ploy
and morphs. The word poly means many and morphs means
different forms. In short, a mechanism by which we can perform
a single action in different ways.

A person in a shop is a customer, in an office, he is an employee,


in the home he is husband/ father/son, in a party he is guest. So,
the same person possesses different roles in different places. It
is called polymorphism.
•Static Polymorphism (Compile Time Polymorphism)
•Dynamic Polymorphism (Run Time Polymorphism)
Method Overloading
• Method overloading occurs within a single class and enables a
class to have more than one method with the same name, as
long as their parameter lists are different.

• It is a compile-time polymorphism technique, meaning the


compiler determines which method to invoke at compile time
based on the method signature.

• Method overloading increases the readability of the program


and avoids the need to create and remember unique method
names for functionalities that are similar but differ in the type
or number of parameters.
class ExampleClass {
void display(int a) {
System.out.println("Display with integer: " + a);
}

void display(String b) {
System.out.println("Display with string: " + b);
}
}
Key Points:

• Same method name, different parameters (either in type,


number, or both).
• Implemented within the same class.
• Helps in increasing the readability of the program.
• It's an example of static polymorphism or compile-time
polymorphism.
Method Overriding
• Method overriding, on the other hand, occurs when a subclass
or child class has a method with the same name, return type,
and parameters as a method in its superclass or parent class.

• It allows a subclass to provide a specific implementation of a


method that is already provided by its superclass.

• Method overriding is a runtime polymorphism technique,


meaning the method that gets executed is determined at
runtime based on the object's runtime type.
Key Points:

❑ Same method name, same parameters as in the superclass.


❑ Occurs between superclass and subclass.
❑ Allows a subclass to provide a specific implementation of a
method.
❑ It's an example of dynamic polymorphism or runtime
polymorphism.
class SuperClass {
void display() {
System.out.println("Display in SuperClass");
}
}

class SubClass extends SuperClass {


@Override
void display() {
System.out.println("Display in SubClass");
}
}
Dynamic Polymorphism
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.

In this process, an overridden method is called through a reference variable of a


superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.

Properties of Dynamic Polymorphism:

It decides which method is to execute at runtime.


It can be achieved through dynamic binding.
It happens between different classes.
It is required where a subclass object is assigned to a super-class object for
dynamic polymorphism.
Inheritance involved in dynamic polymorphism.
Method Overriding
It provides a specific implementation to a method that is already present
in the parent class. it is used to achieve run-time polymorphism. Remember
that, it is not possible to override the static method. Hence, we cannot
override the main() method also because it is a static method.

Rules for Method Overriding

❖ The name of the method must be the same as the name of the parent class
method.
❖ The number of parameters and the types of parameters must be the same as
in the parent class.
❖ There must exist an IS-A relationship (inheritance).
❖ We call an overridden method through a reference of the parent class. The
type of object decides which method is to be executed and it is decided by
the JVM at runtime.
//parent class
class Sample {
public void display() {
System.out.println("Overridden Method"); } }
public class Demo extends Sample {
public void display() {
System.out.println("Overriding Method"); }
public static void main(String args[]) {
//assigning a child class object to parent class reference
Sample obj = new Demo();
//invoking display() method
obj.display(); } }
Example of Method Overriding
public class DynamicPolymorphismExample {
public static void main(String args[]) {
//assigning a child class object to a parent class reference
Fruits fruits = new Mango();
//invoking the method
fruits.color();
} }
//parent class
class Fruits {
public void color() {
System.out.println("Parent class method is invoked."); } }
//derived or child class that extends the parent class
class Mango extends Fruits {
//overrides the color() method of the parent class
@Override
public void color() {
System.out.println("The child class method is invoked."); } }
ABSTRACTION

Abstraction in Java is a concept that helps in hiding the


complex reality while exposing only the necessary features of
an object. In Java, abstraction is achieved using abstract
classes and interfaces.
ABSTRACTION

Abstraction in Java is a concept that helps in hiding the


complex reality while exposing only the necessary
features of an object. In Java, abstraction is achieved
using abstract classes and interfaces.
Abstract Classes

An abstract class in Java is a class that cannot be instantiated


on its own and is meant to be subclassed. It may contain abstract
methods as well as concrete (fully defined) methods. Abstract
classes are used to represent generic concepts or base behaviors
that subclasses should implement or expand upon.
Characteristics of Abstract Classes:
❖ Cannot be instantiated: You cannot create objects of an abstract class
directly.
❖ Can have constructors: Abstract classes can have constructors, and the
constructor is called when a subclass is instantiated.
❖ Can have instance variables: Abstract classes can declare fields that are not
static and final, and define methods that can access and modify the state of
the object to which they belong.
❖ Can have defined methods: Abstract classes can have fully implemented
methods with actual code.
❖ Can have abstract methods: Methods without a body, just declared with the
keyword abstract and a semicolon at the end.
Abstract Methods
Abstract methods are methods declared in an abstract class that do not have an
implementation. Subclasses that extend an abstract class must provide
implementations for its abstract methods unless the subclass is also abstract.

Characteristics of Abstract Methods:


•No body: Abstract methods do not have a body; they're just a signature followed by a
semicolon.
•Implementation by subclasses: Any concrete subclass must implement all inherited
abstract methods, or it too must be declared abstract.
•Enforces a contract: Declaring an abstract method in a class imposes a contract on
the subclasses, obliging them to support particular behaviors.
The Purpose of Abstraction:
❖ To control the complexity of large software systems by hiding
the implementation details and exposing only the necessary
parts of an object.
❖ To provide a common template for subclasses that can be
adapted and implemented as per the subclass's specific
requirements.
❖ To enable code reuse by defining non-specific method signatures
in the parent class that different child classes can share and
implement in different ways.
abstract class Shape {
abstract double area(); }
class Triangle extends Shape {
double base, height;
Triangle(double base, double height) {
this.base = base;
this.height = height; }
@Override
double area() {
return 0.5 * base * height; } }
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width; }
@Override
double area() {
return length * width; }}
public class GeometryTest {
public static void main(String[] args) {
Shape triangle = new Triangle(3, 4);
Shape rectangle = new Rectangle(5, 6);
System.out.println("Triangle area: " + triangle.area());
System.out.println("Rectangle area: " + rectangle.area()); }}
// Declares an abstract class named Shape. An abstract class cannot be instantiated.
abstract class Shape {
// Declares an abstract method named area. It has no body and must be overridden in subclasses.
abstract double area();
}
// Declares a concrete class named Triangle that extends the abstract Shape class.
class Triangle extends Shape {
// Instance variables to store the dimensions of the triangle.
double base, height;
// Constructor for the Triangle class. It initializes the base and height of the triangle.
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
// Overrides the abstract area method from the Shape class. Calculates and returns the area of the triangle.
@Override
double area() {
return 0.5 * base * height;
}
}
// Declares a concrete class named Rectangle that extends the abstract Shape class.
class Rectangle extends Shape {
// Instance variables to store the dimensions of the rectangle.
double length, width;

// Constructor for the Rectangle class. It initializes the length and width of the rectangle.
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Overrides the abstract area method from the Shape class. Calculates and returns the area of the rectangle.
@Override
double area() {
return length * width;
}
}
// Contains the main method, which is the entry point of the program.
public class GeometryTest {
public static void main(String[] args) {
// Creates a Triangle object with base 3 and height 4, referenced by a Shape variable.
Shape triangle = new Triangle(3, 4);
// Creates a Rectangle object with length 5 and width 6, referenced by a Shape variable.
Shape rectangle = new Rectangle(5, 6);
// Calls the area method on the triangle object and prints the result.
System.out.println("Triangle area: " + triangle.area());
// Calls the area method on the rectangle object and prints the result.
System.out.println("Rectangle area: " + rectangle.area());
}
}
// Define an abstract class for a generic payment processor.
abstract class PaymentProcessor {
// Abstract method that needs to be implemented by subclasses to process payments.
abstract void processPayment(double amount);
}

// Subclass of PaymentProcessor for processing credit card payments.


class CreditCardProcessor extends PaymentProcessor {
// Implement the processPayment method for credit card processing.
@Override
void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
// Subclass of PaymentProcessor for processing payments through PayPal.
class PayPalProcessor extends PaymentProcessor {
// Implement the processPayment method for PayPal processing.
@Override
void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
}
// Main class to test the payment processing subclasses.
public class PaymentTest {
public static void main(String[] args) {
// Create an instance of CreditCardProcessor.
PaymentProcessor creditCard = new CreditCardProcessor();
// Create an instance of PayPalProcessor.
PaymentProcessor payPal = new PayPalProcessor();

// Process a payment using the credit card processor.


creditCard.processPayment(100.0);
// Process a payment using the PayPal processor.
payPal.processPayment(200.0);
}
}
Basic Inheritance
Write a Java program where class Vehicle is the superclass with a method displayMaxSpeed() that
prints out a default speed. Class Car extends Vehicle and overrides the displayMaxSpeed() method to
print out a higher speed.

Method Overriding
Write a Java program with a superclass Plant that has a method needsWater() which returns a
boolean value. A subclass Cactus should override this method to return false, signifying that cacti
require less water.

Multi-level Inheritance
Create a Java program with three levels of inheritance. At the top, have a class Instrument with a
method play(). Below it, have a class StringInstrument that extends Instrument. Finally, have a class
Guitar that extends StringInstrument and overrides the play() method to print "Guitar is playing
chords".

Super Keyword
Write a Java program that demonstrates the use of the super keyword to access a superclass's
constructor and methods. Create a superclass Food with a property taste and a method printTaste().
Then, create a subclass Fruit that uses super to set the taste and to invoke the printTaste() method of
Food.

You might also like