0% found this document useful (0 votes)
4 views24 pages

Copy of Session 10 - Classes and Objects - Part 3

The document discusses the use of the final keyword in Java, which is utilized to declare constants, prevent method overriding, and restrict class inheritance. It explains how final can be applied to variables, methods, and classes, providing examples and practice programs for each case. Additionally, it covers argument passing in Java, emphasizing the distinction between passing by value and reference, and introduces the 'this' keyword for referencing the current object instance.

Uploaded by

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

Copy of Session 10 - Classes and Objects - Part 3

The document discusses the use of the final keyword in Java, which is utilized to declare constants, prevent method overriding, and restrict class inheritance. It explains how final can be applied to variables, methods, and classes, providing examples and practice programs for each case. Additionally, it covers argument passing in Java, emphasizing the distinction between passing by value and reference, and introduces the 'this' keyword for referencing the current object instance.

Uploaded by

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

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - II

Session 10 - Classes and Objects -


Part 3

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.

Different places where final keyword is used:


1. final Variables:

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:

a. A method declared as final cannot be overridden by subclasses. This is useful for


methods that are part of a class’s public API and should not be modified by
subclasses.
3. final Classes:

a. A class declared as final cannot be extended or subclassed. This is useful for


preventing inheritance and creating immutable classes.

1. final Keyword in Variables


When a variable is declared as final, its value cannot be changed once it has been initialized.
This is useful for defining constants or values that should remain constant throughout the
program.

● 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:

public class ConstantExample {


public static void main(String[] args) {
final double PI = 3.14159; // Define a constant variable PI
System.out.println("Value of PI: " + PI);
}
}

● Output:

Value of PI: 3.14159

2. final Keyword with Classes

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:

// Immutable class example


final class ImmutablePerson {
private final String name;
private final int age;

public ImmutablePerson(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

@Override
public String toString() {
return "ImmutablePerson{name='" + name + "', age=" + age + "}";
}
}

Usage:

public class Main {


public static void main(String[] args) {
ImmutablePerson person = new ImmutablePerson("John Doe", 30);
System.out.println(person); // Output: ImmutablePerson{name='John Doe',
age=30}
}
}

2. Preventing Subclassing

Example:

// Base class


final class Base {
public void display() {
System.out.println("This is a final class.");
}
}

// Attempting to extend a final class will cause a compile-time error


// class Derived extends Base { }

public class Main {


public static void main(String[] args) {
Base base = new Base();
base.display(); // Output: This is a final class.
}
}

Practice Programs
1. Create a Final Class

Create a final class named Configuration with some configuration settings that cannot be
subclassed.

Example Program:

// Final class


final class Configuration {
private final String setting;

public Configuration(String setting) {


this.setting = setting;
}

public String getSetting() {


return setting;
}
}

public class Main {


public static void main(String[] args) {
Configuration config = new Configuration("High Performance");
System.out.println("Setting: " + config.getSetting());
}
}

3. final Keyword with Methods

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.");
}
}

class DerivedClass extends BaseClass {


// Attempting to override will cause a compile-time error
// void display() {
// System.out.println("Illegal!");
// }
}

public class Main {


public static void main(String[] args) {
BaseClass base = new BaseClass();
base.display(); // Output: This method cannot be overridden.
}
}

2. Security and Consistency

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.");
}
}

class SecureSubclass extends SecureClass {


// Attempting to override will cause a compile-time error
// void authenticate() {
// System.out.println("Modified Authentication.");
// }
}

public class Main {


public static void main(String[] args) {
SecureClass secure = new SecureClass();
secure.authenticate(); // Output: 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.");
}
}

class Car extends Vehicle {


// Attempting to override will cause a compile-time error
// void startEngine() {
// System.out.println("Car engine started.");
// }
}

public class Main {


public static void main(String[] args) {
Car car = new Car();
car.startEngine(); // Output: Engine started.
}
}

2. Prevent Method Overriding
Create a class Account with a final method calculateInterest(). Extend it with a
SavingsAccount class and ensure that calculateInterest() cannot be overridden.

Example Program:

class Account {
final void calculateInterest() {
System.out.println("Calculating interest...");
}
}

class SavingsAccount extends Account {


// Attempting to override will cause a compile-time error
// void calculateInterest() {
// System.out.println("Savings interest calculation.");
// }
}

public class Main {


public static void main(String[] args) {
SavingsAccount savings = new SavingsAccount();
savings.calculateInterest(); // Output: Calculating interest...
}
}

The final keyword in Java is a crucial tool for controlling the behavior of classes and methods.
By using final, you can:

- 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. What does the final keyword do when applied to a class?

A) Prevents the class from being extended

B) Prevents methods from being overridden

C) Makes the class abstract

D) Makes the class static

Answer A) Prevents the class from being extended

2. What is the effect of declaring a method as final?

A) The method becomes abstract

B) The method can be overridden but not modified

C) The method cannot be overridden in subclasses

D) The method can be static

Answer: D) The method cannot be overridden in subclasses

3. Can you extend a final class in Java?


A) Yes, with a different name

B) No, a final class cannot be extended

C) Yes, but only if it is not abstract

D) Yes, if the class has no methods

Answer: B) No, a final class cannot be extended

4. Can you override a final method in Java?

A) Yes, if it is in a different class

B) Yes, but it must be static

C) Yes, but only in the same class

D) No, a final method cannot be overridden

Answer: D) No, a final method cannot be overridden

2. Passing Arguments by Value and by


Reference

Passing Arguments by Value and by Reference


Understanding the Difference

In Java, arguments are passed to methods in a specific way:

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:

- Java does not support pass-by-reference directly. Instead, it passes object


references by value. This means a copy of the reference (i.e., the address of the
object) is passed to the method.
- As a result, while the method receives a reference to the original object, it does
not receive the object itself. Changes made to the object's properties within the
method affect the original object.
Example:

public class ArgumentPassing {


public static void passByValue(int x) {
x = x + 10;
System.out.println("Inside the method: x = " + x);
}

public static void passByReference(Person person) {


person.name = "Alice";
System.out.println("Inside the method: person.name = " + person.name);
}

public static void main(String[] args) {


int num = 5;
passByValue(num);
System.out.println("Outside the method: num = " + num); // Output: 5

Person person = new Person("Bob");


passByReference(person);
System.out.println("Outside the method: person.name = " + person.name); //
Output: Alice
}
}

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.

● passByReference takes a Person object as an argument. A copy of the reference to


person is passed to the method. Modifying the object's properties (like person.name)
inside the method affects the original person object.

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

1. What does Java use to pass primitive data types to methods?

A) By reference

B) By value

C) By object

D) By address

Answer: B) By value

2. When an object is passed to a method in Java, what is passed?

A) A copy of the object

B) The object's value

C) The object reference

D) The object's address

Answer: C) The object reference

3. What happens to the value of a primitive type argument if it is modified inside a


method?

A) The original value changes


B) The original value remains the same

C) The method value becomes final

D) The value cannot be modified

Answer: B) The original value remains the same

4. If an object is passed to a method and its attributes are modified inside the
method, what happens?

A) The original object's attributes are changed

B) The method creates a new object

C) The original object remains unchanged

D) The attributes become final

Answer: A) The original object's attributes are changed

3. ‘this’ keyword in Java

this Keyword in Java


In Java, this is a reference variable that refers to the current object instance. It is an essential
tool for managing and manipulating object properties and methods. Using this can help to
improve code readability and manage object-oriented programming more effectively.

Uses of this
1. Referring to Instance Variables:

- When instance variables are shadowed by method or constructor parameters


with the same name, this can be used to differentiate between them.
2. Invoking Current Class Constructor:

- this() can be used to call another constructor in the same class, which helps
to reduce code duplication.

3. Returning the Current Class Instance:

- this can be used to return the current object instance from a method.

4. Passing Current Object as a Method Parameter:

- this can be passed as a parameter to other methods or constructors.

5. Invoking Current Class Method:

- It can be used to call other methods from within the current method.

6. Using this as an Argument in Constructor Calls:

- this can be used as an argument when creating objects of other classes.

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.

public class Employee {


private String name;
private int id;

// Constructor
public Employee(String name, int id) {
this.name = name; // Refers to the instance variable
this.id = id; // Refers to the instance variable
}

// Method to display employee details


public void displayDetails() {
System.out.println("Employee Name: " + this.name);
System.out.println("Employee ID: " + this.id);
}

public static void main(String[] args) {


Employee emp = new Employee("John Doe", 123);
emp.displayDetails();
}
}

Explanation: In this example, this.name and this.id refer to the instance variables of the
Employee class, distinguishing them from the parameters of the constructor.

2. Invoking Current Class Constructor


Consider a class Rectangle that has two constructors: one default and one parameterized.

public class Rectangle {


private int length;
private int width;

// 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;
}

public void display() {


System.out.println("Length: " + length);
System.out.println("Width: " + width);
}

public static void main(String[] args) {


Rectangle rect = new Rectangle();
rect.display();
}
}

Explanation: The default constructor calls the parameterized constructor using this(10, 5),
which initializes the rectangle with default dimensions.
3. Returning the Current Class Instance
In scenarios where you want to chain method calls, you can return the current object instance.

public class Builder {


private String material;
private int height;

public Builder setMaterial(String material) {


this.material = material;
return this; // Returns the current instance
}

public Builder setHeight(int height) {


this.height = height;
return this; // Returns the current instance
}

public void build() {


System.out.println("Material: " + material);
System.out.println("Height: " + height);
}

public static void main(String[] args) {


Builder builder = new Builder();
builder.setMaterial("Wood").setHeight(10).build();
}
}

Explanation: The setMaterial and setHeight methods return the current instance of
Builder, allowing for method chaining.

4. Passing Current Object as a Method Parameter


If you want to pass the current object to another method, you can use this.

public class Messenger {


private String message;

public Messenger(String message) {


this.message = message;
}

public void sendMessage(Messenger msg) {


System.out.println("Sending message: " + msg.message);
}
public void forwardMessage() {
sendMessage(this); // Passes the current instance
}

public static void main(String[] args) {


Messenger msg = new Messenger("Hello, World!");
msg.forwardMessage();
}
}

Explanation: The forwardMessage method uses this to pass the current instance to the
sendMessage method.

5. Invoking Current Class Method


You can use this to call another method from within the current method.

public class Calculator {


private int value;

public Calculator(int value) {


this.value = value;
}

public void performOperation() {


this.printValue(); // Calls another method in the same class
System.out.println("Performing operation...");
}

private void printValue() {


System.out.println("Value: " + value);
}

public static void main(String[] args) {


Calculator calc = new Calculator(100);
calc.performOperation();
}
}

Explanation: In the performOperation method, this.printValue() is used to call the
printValue method within the same class.

6. Using this as an Argument in Constructor Calls


When you need to pass the current object as an argument to another class, this is helpful.
public class Driver {
private Car car;

public Driver(Car car) {


this.car = car;
this.car.showDetails();
}

public static void main(String[] args) {


Car myCar = new Car("Toyota", "Corolla");
Driver driver = new Driver(myCar); // Passes the Car instance to the Driver
}
}

class Car {
private String make;
private String model;

public Car(String make, String model) {


this.make = make;
this.model = model;
}

public void showDetails() {


System.out.println("Make: " + make);
System.out.println("Model: " + model);
}
}

Explanation: The Driver constructor receives a Car object and calls its showDetails
method.

Advantages of Using this


1. Clarity:

- It helps to differentiate between instance variables and local variables with the
same name.

2. Code Reusability:

- It can invoke other constructors in the same class, reducing redundancy.

3. Method Chaining:
- By returning the current instance, it allows for method chaining.

4. Passing Objects:

- It can be used to pass the current instance to other methods or constructors.

Disadvantages of Using this


1. Overuse:

- Excessive use of this can make the code less readable and harder to
understand.

2. Performance Overhead:

- Unnecessary use of this can add performance overhead.

3. Static Context Restrictions:

- 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

Homework Problems on the this Keyword in Java


1. Create a class Person with name and age as instance variables. Use the this
keyword to initialize these variables in the constructor.
2. Create a class Car with model and color as instance variables. Implement a method
displayCarDetails() that uses the this keyword to access and print the car's
properties.
3. Write a program that demonstrates the use of the this keyword to refer to the current
object within a method. Create a class with a method that prints the object's properties
using this.
4. Consider the following code:

public class MyClass {


int x;

public MyClass(int x) {
this.x = x;
}

public void printX() {


System.out.println(x);
}
}

Explain the purpose of the this keyword in the constructor.
5. Identify the error in the following code:

public class Example {


int x = 10;

public void myMethod() {


int x = 20;
System.out.println(x); // Output: 20
System.out.println(this.x); // Output: 10
}
}

Hint: The this keyword is used to differentiate between instance variables and local variables
with the same name.

Quiz

1. What does the this keyword refer to in a Java class?

A) The class itself

B) The current instance of the class


C) The superclass

D) The method's return type

Answer: B) The current instance of the class

2. How can this be used in a constructor?

A) To call another constructor in the same class

B) To create a new instance of the class

C) To refer to the superclass constructor

D) To access static variables

Answer: A) To call another constructor in the same class

3. When can this be used to differentiate between instance variables and method
parameters?

A) When the variable is final

B) When the method is static

C) When the instance variable and parameter have the same name

D) When the instance variable and parameter have different names

Answer: C) When the instance variable and parameter have the same name

4. Can this be used to access static methods?

A) Yes, this can access all methods

B) No, this is used only for instance methods

C) Yes, but only if they are non-static

D) No, this cannot access static methods

Answer: D) No, this cannot access static methods

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

this keyword - #42 This keyword in Java

End of Session - 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy