Copy of Session 10 - Classes and Objects - Part 3
Copy of Session 10 - Classes and Objects - Part 3
THROUGH JAVA
UNIT - II
1. final keyword
final keyword
The final keyword in Java is used to declare constants, prevent method overriding, and
restrict class inheritance. Here, we'll delve into how final is used with classes and methods,
including syntax, real-time examples, and practice programs.
a. When a variable is declared as final, its value cannot be changed once it has
been initialized. This makes final variables constants.
b. Final variables must be initialized either at the time of declaration or in the
constructor of the class. They cannot be assigned a new value after initialization.
c. If a final variable is a reference, the reference itself cannot be changed, but the
object's internal state can still be modified.
2. final Methods:
● Characteristics:
○ A final variable must be initialized either at the time of declaration or in the
constructor.
○ For reference variables, the reference itself cannot be changed, but the object's
internal state can be modified.
Example:
● Output:
Purpose
Prevent Inheritance: When a class is declared as final, it cannot be subclassed. This is
useful for creating immutable classes or ensuring certain classes are not extended.
Syntax
final class ClassName {
// class body
}
Real-time Examples
1. Immutable Class Example
In Java, the String class is a good example of a final class. By making String final, Java
ensures that the string's behavior remains consistent and cannot be modified.
Example:
@Override
public String toString() {
return "ImmutablePerson{name='" + name + "', age=" + age + "}";
}
}
Usage:
Example:
Practice Programs
1. Create a Final Class
Create a final class named Configuration with some configuration settings that cannot be
subclassed.
Example Program:
Purpose
- Prevent Method Overriding: When a method is declared as final, it cannot be
overridden by subclasses. This ensures that the method's behavior is consistent and
cannot be changed by subclasses.
Syntax
class ClassName {
final void methodName() {
// method body
}
}
Real-time Examples
1. Method Finalization
Example:
class BaseClass {
final void display() {
System.out.println("This method cannot be overridden.");
}
}
Using final methods can be crucial for maintaining consistent behavior in security-sensitive
applications, where altering the behavior of certain methods could introduce vulnerabilities.
Example:
class SecureClass {
final void authenticate() {
System.out.println("Authentication complete.");
}
}
Practice Programs
1. Implement Final Method
Create a base class Vehicle with a final method startEngine(). Extend it with a Car
class and ensure that startEngine() cannot be overridden.
Example Program:
class Vehicle {
final void startEngine() {
System.out.println("Engine started.");
}
}
Example Program:
class Account {
final void calculateInterest() {
System.out.println("Calculating interest...");
}
}
- Create immutable classes: Ensuring that certain classes cannot be extended, thus
preserving their behavior and integrity.
- Prevent method overriding: Protecting critical methods from being altered in
subclasses, ensuring consistent behavior.
Understanding and utilizing the final keyword helps in designing robust, secure, and
maintainable Java applications.
Do It Yourself
1. Write a Java program that defines a class Circle with a final variable PI and a
method calculateCircumference(double radius) to compute the circumference
of the circle. Show that the PI variable cannot be reassigned.
2. Create a Java program with an Animal class that includes a final method
makeSound(). Then, create a subclass Dog and attempt to override the makeSound()
method. Demonstrate that overriding a final method results in a compilation error.
Quiz
1. Pass by Value:
- In Java, all arguments are passed by value. This means that a copy of the
argument's value is passed to the method.
- For primitive data types (e.g., int, double, boolean), this means a copy of the
actual value is used within the method. Changes made to this copy do not affect
the original value outside the method.
-
2. Pass by Reference:
class Person {
String name;
Person(String name) {
this.name = name;
}
}
In this example:
● passByValue takes an int as an argument. A copy of num is created and used within
the method. Modifying x inside the method does not affect the original num value.
Key Points:
● Java always uses pass-by-value for method arguments. For primitives, it’s a copy of the
actual value. For objects, it’s a copy of the reference to the object.
● Modifications to primitive values inside methods do not affect the original values.
● Modifications to an object's properties inside a method affect the original object because
the method operates on the reference to the same object.
Additional Considerations:
● When dealing with objects, be cautious about modifying their state within methods, as it
can lead to unintended side effects.
● To avoid modifying the original object, you can create a copy of the object before
passing it to the method, either through cloning or other means.
By understanding how arguments are passed in Java, you can better manage how data is
shared and modified within your methods, leading to more predictable and reliable code.
Do It Yourself
1. Write a program that demonstrates passing a primitive data type and an object to a
method. Show how changes to these parameters within the method affect the original
values. Document the findings and provide explanations.
2. Create a Java class Box with a field size and a method updateSize(int newSize). Write a
program that passes a Box object to the updateSize method and modifies the size field.
Show that the size field of the original Box object is updated.
3. Write a Java program with a class Student that has a field grade. Create a method
changeGrade(Student student, int newGrade) which updates the grade field
of the Student object. Pass a Student object and a new grade to this method and
observe how the Student object’s grade changes.
Quiz
A) By reference
B) By value
C) By object
D) By address
Answer: B) By value
4. If an object is passed to a method and its attributes are modified inside the
method, what happens?
Uses of this
1. Referring to Instance Variables:
- this() can be used to call another constructor in the same class, which helps
to reduce code duplication.
- this can be used to return the current object instance from a method.
- It can be used to call other methods from within the current method.
Examples
Imagine a scenario where you are building a class for managing employee records. Each
employee has a name and an ID number. When updating the employee details, you might want
to distinguish between the instance variables and the method parameters.
// Constructor
public Employee(String name, int id) {
this.name = name; // Refers to the instance variable
this.id = id; // Refers to the instance variable
}
// Default constructor
public Rectangle() {
this(10, 5); // Calls the parameterized constructor
}
// Parameterized constructor
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
class Car {
private String make;
private String model;
- It helps to differentiate between instance variables and local variables with the
same name.
2. Code Reusability:
3. Method Chaining:
- By returning the current instance, it allows for method chaining.
4. Passing Objects:
- Excessive use of this can make the code less readable and harder to
understand.
2. Performance Overhead:
- this cannot be used in static methods or static contexts, as they do not belong
to any instance.
The this keyword is a versatile and useful feature in Java that facilitates working with object-
oriented programming. By understanding its applications and limitations, you can effectively
manage and manipulate object instances in your programs.
Do It Yourself
public MyClass(int x) {
this.x = x;
}
Quiz
3. When can this be used to differentiate between instance variables and method
parameters?
C) When the instance variable and parameter have the same name
Answer: C) When the instance variable and parameter have the same name
References
final keyword - #57 Final keyword in java
Passing arguments by Value - Passing Arguments by Value in Java
Passing arguments by Reference - Passing Arguments by Reference in Java
End of Session - 10