0% found this document useful (0 votes)
2 views34 pages

Java Lab 4

Uploaded by

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

Java Lab 4

Uploaded by

nabiha.fiza
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Department of CSE, CUET Java OOP Lab Sheet

Lab Sheet: Final Keyword, Polymorphism, and


Abstraction in Java
Course: Introduction to Programming Language II (Java)
Topic: Final Keyword, Reference Type vs. Object Type, Dynamic Dispatch,
Abstraction, Abstract Classes, Interfaces
Level: Beginner to Intermediate
Duration: 3 hours
Prepared by: Ashraful Islam Paran, Dept. of CSE, SEU

1. Objectives
By the end of this lab, students will be able to:
• Understand and apply the final keyword to variables, methods, and classes.
• Differentiate between reference type and object type in Java.
• Implement dynamic dispatch and runtime polymorphism.
• Use abstract classes and interfaces for abstraction.
• Resolve ambiguities like the diamond problem using interfaces.
• Practice coding with examples and exercises on these topics.

2. The final Keyword


The final keyword in Java is used to restrict modifications. It can be applied to vari-
ables (making them constants), methods (preventing overriding), and classes (preventing
inheritance). Key Points:
• Final Variables: Constants that cannot be reassigned. Must be initialized at
declaration or in a constructor (for non-static) or static block (for static).
• Blank Final Variables: Declared without initialization but must be assigned once
in a constructor.
• Static Blank Final Variables: Assigned once in a static block.
• Final Methods: Cannot be overridden in subclasses.
• Final Classes: Cannot be extended.

3. Example 1: Final Variable

public class FinalVariableExample {


public static void main(String[] args) {
final int MAX = 100;
[Link]("MAX: " + MAX);
// MAX = 200; // Error
}
}

Prepared by Ashraful Islam Paran


Page 1
Department of CSE, CUET Java OOP Lab Sheet

Output:

MAX: 100

4. Example 2: Blank Final Variable

class BlankFinalExample {
final int speed; // blank final
BlankFinalExample(int s) {
speed = s; // must assign value here
}
void showSpeed() {
[Link]("Speed: " + speed);
}
public static void main(String[] args) {
BlankFinalExample obj = new BlankFinalExample(90);
[Link](); // Output: Speed: 90
}
}

Output:

Speed: 90

5. Example 3: Static Blank Final Variable

class StaticBlankFinalExample {
static final int MAX;
static {
MAX = 500; // must initialize here
}
public static void main(String[] args) {
[Link]("MAX: " + MAX); // Output: MAX: 500
}
}

Output:

MAX: 500

Prepared by Ashraful Islam Paran


Page 2
Department of CSE, CUET Java OOP Lab Sheet

6. Example 4: Final Method

class Parent {
final void show() {
[Link]("Final method in Parent");
}
}

class Child extends Parent {


// void show() { } // Error: cannot override final method
}

public class FinalMethodExample {


public static void main(String[] args) {
new Child().show(); // Output: Final method in Parent
}
}

Output:

Final method in Parent

7. Example 5: Final Class

final class Vehicle {


void run() {
[Link]("Vehicle is running");
}
}

// class Car extends Vehicle {} // Error

public class FinalClassExample {


public static void main(String[] args) {
Vehicle v = new Vehicle();
[Link](); // Output: Vehicle is running
}
}

Output:

Vehicle is running

Task 2.1 – Final Variable Practice (10 min)

a. Create a class Constants with final variables for PI (3.14159) and GRAVITY
(9.8). Write a main method to print them. Attempt to reassign one and note the
error.

Prepared by Ashraful Islam Paran


Page 3
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
public class Constants {
public static void main(String[] args) {
final double PI = 3.14159;
final double GRAVITY = 9.8;
[Link]("PI: " + PI);
[Link]("GRAVITY: " + GRAVITY);
// PI = 3.14; // Error
}
}

Prepared by Ashraful Islam Paran


Page 4
Department of CSE, CUET Java OOP Lab Sheet

Task 2.2 – Blank Final in Constructor (10 min)

a. Create a class Person with a blank final String name. Initialize it in the construc-
tor. Add a method to display the name.

Prepared by Ashraful Islam Paran


Page 5
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
class Person {
final String name;
Person(String n) {
name = n;
}
void display() {
[Link]("Name: " + name);
}
public static void main(String[] args) {
Person p = new Person("Alice");
[Link](); // Output: Name: Alice
}
}

Task 2.3 – Static Blank Final (10 min)

a. Create a class Config with a static blank final int PORT. Initialize it in a static
block to 8080. Print it in main.

Prepared by Ashraful Islam Paran


Page 6
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
class Config {
static final int PORT;
static {
PORT = 8080;
}
public static void main(String[] args) {
[Link]("PORT: " + PORT); // Output: PORT: 8080
}
}

Task 2.4 – Final Method and Class (10 min)

a. Create a final class MathUtils with a final method add(int a, int b) that
returns the sum. Try to extend the class and override the method (note errors).

Prepared by Ashraful Islam Paran


Page 7
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
final class MathUtils {
final int add(int a, int b) {
return a + b;
}
}

// class ExtendedMath extends MathUtils {} // Error

public class MathTest {


public static void main(String[] args) {
MathUtils mu = new MathUtils();
[Link]([Link](5, 3)); // Output: 8
}
}

Prepared by Ashraful Islam Paran


Page 8
Department of CSE, CUET Java OOP Lab Sheet

8. Reference Type vs. Object Type and Dynamic Dispatch


Reference type is the declared type of a variable (compile-time), while object type is
the actual type in memory (runtime). Dynamic dispatch resolves overridden methods at
runtime based on object type. Key Points:
• Reference Type: Determines accessible methods/fields at compile-time. From
left side of assignment.
• Object Type: Determines which overridden methods run at runtime. From right
side of assignment.
• Dynamic Dispatch: Overridden methods are called based on object type (runtime
polymorphism).
• Variables and non-overridden methods are resolved by reference type.
• Fields are not polymorphic; resolved by reference type.
• Casting allows access to subclass members.

9. Example 6: Basic Reference vs Object Type

// Reference type: Parent


Parent p = new Child(); // Object type: Child

10. Example 7: Parent-Child Example

class Parent {
int x = 10;
void speak() {
[Link]("Parent speaks");
}
}
class Child extends Parent {
int x = 20;
@Override
void speak() {
[Link]("Child speaks");
}
void onlyChildDoes() {
[Link]("Child-only method");
}
}
public class Test {
public static void main(String[] args) {
Parent p = new Child(); // ref: Parent, obj: Child
[Link](p.x); // 10 (reference type wins)
[Link](); // Child speaks (object type wins)
// [Link](); // Compile error (Parent doesn’t have
,→ this method)
((Child) p).onlyChildDoes(); // OK after casting
}
}

Prepared by Ashraful Islam Paran


Page 9
Department of CSE, CUET Java OOP Lab Sheet

Output:

10
Child speaks
Child-only method

Prepared by Ashraful Islam Paran


Page 10
Department of CSE, CUET Java OOP Lab Sheet

11. Example 8: Animal-Dog-Cat Example

class Animal {
String name = "Animal";
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
String name = "Dog";
@Override
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
String name = "Cat";
@Override
void sound() {
[Link]("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Dog(); // parent reference, child object
Animal a2 = new Cat(); // parent reference, child object
Animal a3 = new Animal(); // parent reference, parent object
// --- Dynamic Dispatch in action ---
[Link](); // Dog barks
[Link](); // Cat meows
[Link](); // Animal makes a sound
// --- Variable behavior ---
[Link]([Link]); // Animal
[Link]([Link]); // Animal
[Link]([Link]); // Animal
}
}

Output:

Dog barks
Cat meows
Animal makes a sound
Animal
Animal
Animal

Task 3.1 – Reference vs Object Type (12 min)

a. Create classes Vehicle (with int speed = 50, void move()) and Car extends
Vehicle (speed = 100, override move()). Use Vehicle ref = new Car() and print
speed/move.

Prepared by Ashraful Islam Paran


Page 11
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
class Vehicle {
int speed = 50;
void move() {
[Link]("Vehicle moves");
}
}
class Car extends Vehicle {
int speed = 100;
@Override
void move() {
[Link]("Car drives");
}
}
public class VehicleTest {
public static void main(String[] args) {
Vehicle v = new Car();
[Link]([Link]); // 50 (reference type)
[Link](); // Car drives (object type)
}
}

Prepared by Ashraful Islam Paran


Page 12
Department of CSE, CUET Java OOP Lab Sheet

Task 3.2 – Dynamic Dispatch with Casting (12 min)

a. Add a method honk() to Car only. Use casting to call it from Vehicle reference.

Prepared by Ashraful Islam Paran


Page 13
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
// Extend from above
class Car extends Vehicle {
// ... (previous)
void honk() {
[Link]("Car honks");
}
}
public class VehicleTest {
public static void main(String[] args) {
Vehicle v = new Car();
// [Link](); // Compile error
((Car) v).honk(); // Car honks
}
}

Task 3.3 – Multiple Subclasses (12 min)

a. Create Bird extends Animal (name = ”Bird”, override sound() to ”Bird chirps”).
Use Animal refs for Dog, Cat, Bird and call sound()/print name.

Prepared by Ashraful Islam Paran


Page 14
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
// Extend from Animal example
class Bird extends Animal {
String name = "Bird";
@Override
void sound() {
[Link]("Bird chirps");
}
}
public class Main {
public static void main(String[] args) {
Animal a4 = new Bird();
[Link](); // Bird chirps
[Link]([Link]); // Animal
}
}

Prepared by Ashraful Islam Paran


Page 15
Department of CSE, CUET Java OOP Lab Sheet

12. Abstraction, Abstract Classes, and Interfaces


Abstraction hides implementation details. Achieved via abstract classes (partial abstrac-
tion) or interfaces (full abstraction). Key Points:

• Abstract Class: Can have abstract (no body) and concrete methods, fields, con-
structors. Cannot instantiate. Subclasses must implement abstract methods.

• Interface: All methods abstract/public by default, variables public static final.


Supports multiple inheritance. No constructors/instance fields.

• Differences: Interfaces are 100% abstract, abstract classes can have defaults.

• Diamond Problem: Java avoids with classes; resolves in interfaces by overriding.

• Multiple inheritance via interfaces is safe due to no implementations.

13. Example 9: Abstract Class Basic Example

abstract class Animal {


// Abstract method (no body)
abstract void sound();
// Concrete method
void sleep() {
[Link]("Animal is sleeping...");
}
}
// Concrete subclass
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Output: Dog barks
[Link](); // Output: Animal is sleeping...
}

Output:

Dog barks
Animal is sleeping...

Prepared by Ashraful Islam Paran


Page 16
Department of CSE, CUET Java OOP Lab Sheet

14. Example 10: Abstract Subclass Example

abstract class Animal {


abstract void sound();
void sleep() {
[Link]("Animal is sleeping...");
}
}
abstract class Dog extends Animal {
void bark() {
[Link]("Dog barking behavior");
}
}
class Beagle extends Dog {
@Override
void sound() {
[Link]("Beagle barks");
}
}
public class MainClass {
public static void main(String[] args) {
Dog d = new Beagle(); // Dog reference to Beagle object
[Link](); // Output: Beagle barks
[Link](); // Output: Dog barking behavior
[Link](); // Output: Animal is sleeping...
}
}

Output:

Beagle barks
Dog barking behavior
Animal is sleeping...

Prepared by Ashraful Islam Paran


Page 17
Department of CSE, CUET Java OOP Lab Sheet

15. Example 11: Vehicle Abstract Example

abstract class Vehicle {


abstract void start();
abstract void stop();
void fuelType() {
[Link]("Uses fuel");
}
}
class Car extends Vehicle {
void start() {
[Link]("Car starts with key");
}
void stop() {
[Link]("Car stops with brakes");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
[Link](); // Car starts with key
[Link](); // Car stops with brakes
[Link](); // Uses fuel
}
}

Output:

Car starts with key


Car stops with brakes
Uses fuel

Prepared by Ashraful Islam Paran


Page 18
Department of CSE, CUET Java OOP Lab Sheet

16. Example 12: Shape Abstract with Constructor

abstract class Shape {


String color;
Shape(String color) {
[Link] = color;
}
abstract double area();
void displayColor() {
[Link]("Color: " + color);
}
}
class Circle extends Shape {
double radius;
Circle(String color, double radius) {
super(color);
[Link] = radius;
}
double area() {
return [Link] * radius * radius;
}
}

17. Example 13: Employee Abstract Example

abstract class Employee {


abstract void calculateSalary();
}
class FullTimeEmployee extends Employee {
void calculateSalary() {
[Link]("Salary: Fixed monthly salary");
}
}
class PartTimeEmployee extends Employee {
void calculateSalary() {
[Link]("Salary: Hourly based salary");
}
}
public class Main {
public static void main(String[] args) {
Employee e1 = new FullTimeEmployee();
Employee e2 = new PartTimeEmployee();
[Link](); // Salary: Fixed monthly salary
[Link](); // Salary: Hourly based salary
}
}

Output:

Salary: Fixed monthly salary


Salary: Hourly based salary

Prepared by Ashraful Islam Paran


Page 19
Department of CSE, CUET Java OOP Lab Sheet

18. Example 14: Interface Basic Example

interface Flyable {
// Variable must be static and final
int MAX_ALTITUDE = 10000; // implicitly public static final
void fly(); // implicitly public and abstract
}

19. Example 15: Bank Interface Example

interface Bank {
double INTEREST_RATE = 5.5;
void calculateInterest();
}

class CityBank implements Bank {


public void calculateInterest() {
[Link]("Interest Rate: " + INTEREST_RATE + "%");
}
}

20. Example 16: Shape Interface Example

interface Shape {
double pi = 3.1416;
double area();
}
class Circle implements Shape {
double r = 2;
public double area() {
return pi * r * r;
}
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle();
[Link]([Link]());
[Link]([Link]);
[Link]([Link]);
}
}

Prepared by Ashraful Islam Paran


Page 20
Department of CSE, CUET Java OOP Lab Sheet

21. Example 17: Multiple Interfaces Example

interface Printable {
void print();
}
interface Scannable {
void scan();
}
class Printer implements Printable, Scannable {
public void print() {
[Link]("Printing document");
}
public void scan() {
[Link]("Scanning document");
}
}

22. Example 18: Payment Interface Example

interface Payment {
void pay();
}
class CreditCardPayment implements Payment {
public void pay() {
[Link]("Paid using credit card");
}
}
class MobileBankingPayment implements Payment {
public void pay() {
[Link]("Paid using mobile banking");
}
}
public class Main {
public static void main(String[] args) {
Payment p1 = new CreditCardPayment();
[Link](); // Paid using credit card
Payment p2 = new MobileBankingPayment();
[Link](); // Paid using mobile banking
}
}

Output:

Paid using credit card


Paid using mobile banking

Prepared by Ashraful Islam Paran


Page 21
Department of CSE, CUET Java OOP Lab Sheet

23. Example 19: Abstract Class + Interface Example

abstract class Animal {


abstract void sound();
void sleep() {
[Link]("Sleeping...");
}
}
// Interface
interface Pet {
void play();
}
class Dog extends Animal implements Pet {
public void sound() {
[Link]("Bark");
}
public void play() {
[Link]("Plays fetch");
}
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Output: Bark
[Link](); // Output: Plays fetch
[Link](); // Output: Sleeping...
}
}

Output:
Bark
Plays fetch
Sleeping...

24. Example 20: Diamond Problem Example (Classes - Error)

class A {
void show() {
[Link]("A’s show");
}
}

class C extends A {
void show() {
[Link]("C’s show");
}
}

class B extends A {
void show() {
[Link]("B’s show");
}
}

// class D extends B, C { // Ambiguous: which show() method to inherit? }

// Compile error: Java does not allow multiple inheritance with classes

Prepared by Ashraful Islam Paran


Page 22
Department of CSE, CUET Java OOP Lab Sheet

25. Example 21: Diamond Problem Solution (Interfaces)

interface A {
default void show() {
[Link]("Interface A");
}
}
interface B {
default void show() {
[Link]("Interface B");
}
}
class Demo implements A, B {
public void show() {
[Link]();
}
}
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
[Link](); // Interface A
}
}

Output:

Interface A

26. Example 22: Multiple Inheritance with Interfaces Example

interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
public void fly() {
[Link]("Duck is flying");
}
public void swim() {
[Link]("Duck is swimming");
}
public static void main(String[] args) {
Duck d = new Duck();
[Link](); // Output: Duck is flying
[Link](); // Output: Duck is swimming
}
}

Output:

Duck is flying
Duck is swimming

Prepared by Ashraful Islam Paran


Page 23
Department of CSE, CUET Java OOP Lab Sheet

Task 4.1 – Abstract Class Practice (15 min)

a. Create abstract class Device with abstract void powerOn() and concrete void
checkBattery(). Subclass Phone implements powerOn().

Prepared by Ashraful Islam Paran


Page 24
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
abstract class Device {
abstract void powerOn();
void checkBattery() {
[Link]("Battery level: 100%");
}
}
class Phone extends Device {
@Override
void powerOn() {
[Link]("Phone powering on");
}
}
public class DeviceTest {
public static void main(String[] args) {
Device d = new Phone();
[Link](); // Phone powering on
[Link](); // Battery level: 100%
}
}

Task 4.2 – Abstract with Constructor (15 min)

a. Create abstract Fruit with String color (via constructor) and abstract void taste().
Subclass Apple.

Prepared by Ashraful Islam Paran


Page 25
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
abstract class Fruit {
String color;
Fruit(String color) {
[Link] = color;
}
abstract void taste();
void displayColor() {
[Link]("Color: " + color);
}
}
class Apple extends Fruit {
Apple(String color) {
super(color);
}
@Override
void taste() {
[Link]("Sweet");
}
}
public class FruitTest {
public static void main(String[] args) {
Apple a = new Apple("Red");
[Link](); // Sweet
[Link](); // Color: Red
}
}

Prepared by Ashraful Islam Paran


Page 26
Department of CSE, CUET Java OOP Lab Sheet

Task 4.3 – Interface Practice (15 min)

a. Create interface Drawable with void draw() and constant int SIZE = 10. Imple-
ment in class Square.

Prepared by Ashraful Islam Paran


Page 27
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
interface Drawable {
int SIZE = 10;
void draw();
}
class Square implements Drawable {
public void draw() {
[Link]("Drawing square of size " + SIZE);
}
}
public class DrawTest {
public static void main(String[] args) {
Square s = new Square();
[Link](); // Drawing square of size 10
}
}

Task 4.4 – Multiple Interfaces (15 min)

a. Create interfaces Readable (void read()) and Writable (void write()). Class
Book implements both.

Prepared by Ashraful Islam Paran


Page 28
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
interface Readable {
void read();
}
interface Writable {
void write();
}
class Book implements Readable, Writable {
public void read() {
[Link]("Reading book");
}
public void write() {
[Link]("Writing book");
}
}
public class BookTest {
public static void main(String[] args) {
Book b = new Book();
[Link](); // Reading book
[Link](); // Writing book
}
}

Prepared by Ashraful Islam Paran


Page 29
Department of CSE, CUET Java OOP Lab Sheet

Task 4.5 – Abstract Class + Interface (15 min)

a. Abstract class Gadget (abstract void operate()) + interface Chargeable (void


charge()). Class Laptop extends/implements both.

Prepared by Ashraful Islam Paran


Page 30
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
abstract class Gadget {
abstract void operate();
}
interface Chargeable {
void charge();
}
class Laptop extends Gadget implements Chargeable {
@Override
void operate() {
[Link]("Laptop operating");
}
@Override
void charge() {
[Link]("Laptop charging");
}
}
public class GadgetTest {
public static void main(String[] args) {
Laptop l = new Laptop();
[Link](); // Laptop operating
[Link](); // Laptop charging
}
}

Task 4.6 – Diamond Problem Resolution (15 min)

a. Interfaces SoundA and SoundB both with default void makeSound(). Class Speaker
implements both and overrides.

Prepared by Ashraful Islam Paran


Page 31
Department of CSE, CUET Java OOP Lab Sheet

Sample Code:
interface SoundA {
default void makeSound() {
[Link]("Sound A");
}
}
interface SoundB {
default void makeSound() {
[Link]("Sound B");
}
}
class Speaker implements SoundA, SoundB {
@Override
public void makeSound() {
[Link](); // Choose A
}
}
public class SoundTest {
public static void main(String[] args) {
Speaker s = new Speaker();
[Link](); // Sound A
}
}

Prepared by Ashraful Islam Paran


Page 32
Department of CSE, CUET Java OOP Lab Sheet

27. Key Differences: Abstract Class vs Interface

Interface Abstract Class


Java interface are implicitly abstract and cannot have implementations A Java abstract class can ha
Variables declared in a Java interface is by default final An abstract class may conta
Members of a Java interface are public by default A Java abstract class can ha
Java interface should be implemented using keyword “implements” A Java abstract class should
An interface can extend another Java interface only an abstract class can extend
Interface is absolutely abstract and cannot be instantiated A Java abstract class also c
java interfaces are slow as it requires extra indirection Comparatively fast

28. Summary Table

Concept Description Example


Final Variable Constant, cannot reassign final int MAX = 100;
Final Method Cannot override final void show()
Final Class Cannot extend final class Vehicle
Reference Type Compile-time type Parent p = new Child(); (Parent)
Object Type Runtime type Parent p = new Child(); (Child)
Dynamic Dispatch Runtime method resolution [Link]() calls Child’s version
Abstract Class Partial abstraction abstract class Animal
Interface Full abstraction interface Flyable
Diamond Problem Ambiguity in multiple inheritance Resolved by overriding in interfaces

29. Final Task


Design a system using abstraction and polymorphism:

• Abstract class Shape with abstract area() and perimeter().

• Concrete classes Circle and Rectangle.

• Interface Resizable with resize(double factor).

• Make Rectangle implement Resizable.

• Use polymorphism to compute areas in a list of shapes.

Use final where appropriate.

30. Practice Questions


1. Explain the difference between reference type and object type.

2. What is dynamic dispatch, and when does it occur?

3. Why can’t abstract classes be instantiated?

Prepared by Ashraful Islam Paran


Page 33
Department of CSE, CUET Java OOP Lab Sheet

4. How does Java handle multiple inheritance?

5. Write a program using an interface with default methods and resolve a diamond
problem.

6. What happens if a subclass doesn’t implement an abstract method?

Keep Coding!

Prepared by Ashraful Islam Paran


Page 34

You might also like