Chapter 4 Java
Chapter 4 Java
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
}
}
Example 2: Method Overriding
// Superclass
class Vehicle {
void start() {
System.out.println("Vehicle is starting.");
}
}
// Subclass
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start(); // Calls the overridden method in Car
}
}
// Superclass
class Shape {
void display() {
System.out.println("This is a shape.");
}
}
// Intermediate subclass
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle.");
}
}
// Leaf subclass
class ColoredCircle extends Circle {
void fillColor() {
System.out.println("Filling the circle with color.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
ColoredCircle coloredCircle = new ColoredCircle();
coloredCircle.display(); // Inherited from Shape
coloredCircle.draw(); // From Circle
coloredCircle.fillColor(); // From ColoredCircle
}
}
Person(String name) {
this.name = name;
}
}
// Subclass
class Student extends Person {
int studentId;
void display() {
System.out.println("Name: " + name + ", Student ID: " +
studentId);
}
}
// Usage
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 101);
student.display(); // Output: Name: Alice, Student ID: 101
}
}
// Abstract superclass
abstract class Animal {
abstract void sound(); // Abstract method
}
// Subclass
class Cat extends Animal {
@Override
void sound() {
System.out.println("The cat meows.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.sound(); // Output: The cat meows.
}
}
// Superclass
class Game {
void start() {
System.out.println("Game is starting.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Soccer soccer = new Soccer();
soccer.start(); // From Game
soccer.play(); // From Playable
}
}
// Usage
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
@Override
public double area() {
return width * height;
}
}
class Circle implements Shape {
private double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
// Usage
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Rectangle(4, 5), new Circle(3) };
@Override
public void eat() {
System.out.println("Dog is eating.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.play(); // Output: Dog is playing.
dog.eat(); // Output: Dog is eating.
}
}
// Usage
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // Output: Car is starting.
car.honk(); // Output: Vehicle is honking.
}
}
Car() {
this.engine = new Engine(); // Composition
}
void startCar() {
engine.start(); // Delegating the start action to the engine
System.out.println("Car is ready to go!");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.startCar();
// Output:
// Engine starting...
// Car is ready to go!
}
}
Car() {
this.engine = new Engine();
this.wheels = new Wheel[4]; // A car typically has 4 wheels
for (int i = 0; i < wheels.length; i++) {
wheels[i] = new Wheel();
}
}
void startCar() {
engine.start();
for (Wheel wheel : wheels) {
wheel.roll();
}
System.out.println("Car is ready to go!");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.startCar();
// Output:
// Engine starting...
// Wheel is rolling.
// Wheel is rolling.
// Wheel is rolling.
// Wheel is rolling.
// Car is ready to go!
}
}
FlyingMachine(Flyable flyable) {
this.flyable = flyable;
}
void performFlight() {
flyable.fly(); // Delegating the flight action
}
}
// Usage
public class Main {
public static void main(String[] args) {
FlyingMachine birdMachine = new FlyingMachine(new Bird());
FlyingMachine planeMachine = new FlyingMachine(new
Plane());
Configuration(String setting) {
this.setting = setting;
}
String getSetting() {
return setting;
}
}
Application(Configuration config) {
this.config = config;
}
void run() {
System.out.println("Application running with setting: " +
config.getSetting());
}
}
// Usage
public class Main {
public static void main(String[] args) {
Configuration config = new Configuration("High Performance");
Application app = new Application(config);
app.run(); // Output: Application running with setting: High
Performance
}
}
Document(Printer printer) {
this.printer = printer; // Dependency injection
}
// Usage
public class Main {
public static void main(String[] args) {
Printer printer = new Printer();
Document doc = new Document(printer);
doc.printDocument("Hello, World!"); // Output: Printing: Hello,
World!
}
}
HomeTheater() {
this.soundSystem = new SoundSystem(); // Composition
}
void watchMovie() {
System.out.println("Setting up the home theater...");
soundSystem.playMusic(); // Using the composed object
System.out.println("Enjoy the movie!");
}
}
// Usage
public class Main {
public static void main(String[] args) {
HomeTheater homeTheater = new HomeTheater();
homeTheater.watchMovie();
// Output:
// Setting up the home theater...
// Playing music...
// Enjoy the movie!
}
}
Q5: What is the DRY principle, and how does it relate to code
reusability?
A: The DRY (Don't Repeat Yourself) principle emphasizes reducing
code duplication. By reusing code through methods, classes, or
libraries, developers can adhere to this principle, making their
codebase cleaner and easier to maintain.
Q6: How can libraries and frameworks aid in code
reusability?
A: Libraries and frameworks provide pre-written code for common
tasks, allowing developers to leverage existing solutions rather than
creating new ones. This accelerates development and ensures
consistency across applications.
Q7: What role do design patterns play in code reusability?
A: Design patterns are established solutions to common problems in
software design. By following these patterns, developers can create
reusable code structures that facilitate easier maintenance and
scalability.
Q8: How can generic programming enhance code reusability
in Java?
A: Generic programming allows developers to define classes,
interfaces, and methods with type parameters. This enables the
creation of flexible and reusable code that can work with any data
type, reducing redundancy.
Q9: What is the significance of modular programming in
terms of code reusability?
A: Modular programming involves breaking down a program into
smaller, manageable, and reusable modules. This makes it easier to
test, maintain, and reuse code across different projects.
Q10: Can you provide an example of how to achieve code
reusability with methods in Java?
A: Yes! Here’s a simple example:
java
Copy
public class MathUtils {
// Method to add two numbers
public static int add(int a, int b) {
return a + b;
}
// Usage
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 10);
System.out.println("Sum: " + sum); // Output: Sum: 15
}
}
// Usage
public class Main {
public static void main(String[] args) {
String original = "Hello";
String reversed = StringUtils.reverse(original);
System.out.println("Reversed: " + reversed); // Output:
Reversed: olleH
}
}
// Usage
public class Main {
public static void main(String[] args) {
Config.displayConfig(); // Output: Application Configuration
Loaded
}
}
void showMessage() {
System.out.println("Hello from Singleton!");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.showMessage(); // Output: Hello from Singleton!
}
}
// Usage
public class Main {
public static void main(String[] args) {
Display.show(100); // Output: Integer: 100
Display.show("Hello!"); // Output: Message: Hello!
}
}
Example 7: Static Methods in a Math Library
class MathLibrary {
// Static method to compute the factorial of a number
static long factorial(int n) {
if (n == 0) return 1;
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
// Usage
public class Main {
public static void main(String[] args) {
int number = 5;
long fact = MathLibrary.factorial(number);
System.out.println("Factorial of " + number + " is " + fact); //
Output: Factorial of 5 is 120
}
}
src/
└── com/
└── example/
└── utils/
└── MathUtils.java
// File: src/com/example/utils/MathUtils.java
package com.example.utils;
// File: src/Main.java
import com.example.utils.MathUtils;
}
}
└── com/
└── example/
└── shapes/
├── Circle.java
└── Rectangle.java
Circle Class
// File: src/com/example/shapes/Circle.java
package com.example.shapes;
this.radius = radius;
Rectangle Class
// File: src/com/example/shapes/Rectangle.java
package com.example.shapes;
this.width = width;
this.height = height;
// File: src/Main.java
import com.example.shapes.Circle;
import com.example.shapes.Rectangle;
src/
└── com/
└── example/
└── animals/
├── Dog.java
└── Cat.java
Dog Class
// File: src/com/example/animals/Dog.java
package com.example.animals;
System.out.println("Dog barks!");
Cat Class
// File: src/com/example/animals/Cat.java
package com.example.animals;
System.out.println("Cat meows!");
// File: src/Main.java
import com.example.animals.Dog;
import com.example.animals.Cat;
public class Main {
Example 4: Subpackages
1. Creating a Subpackage
src/
└── com/
└── example/
├── animals/
│ ├── Dog.java
│ └── Cat.java
└── services/
└── AnimalService.java
AnimalService Class
// File: src/com/example/services/AnimalService.java
package com.example.services;
import com.example.animals.Dog;
import com.example.animals.Cat;
dog.bark();
cat.meow();
// File: src/Main.java
import com.example.services.AnimalService;
animalService.makeSound();
// Output:
// Dog barks!
// Cat meows!
// File: src/com/example/animals/Cat.java
package com.example.animals;
System.out.println("Cat meows!");
// File: src/com/example/animals/Dog.java
package com.example.animals;
System.out.println("Dog barks!");
// File: src/Main.java
import com.example.animals.Dog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();
// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks!
myDog.sleep(); // Output: Sleeping...
}
}
// Constructor
Vehicle(String brand) {
this.brand = brand;
}
// Abstract method
abstract void start();
// Concrete method
String getBrand() {
return brand;
}
}
@Override
void start() {
System.out.println(getBrand() + " car is starting.");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car("Toyota");
myCar.start(); // Output: Toyota car is starting.
}
}
// Abstract class
abstract class Shape {
abstract double area(); // Abstract method
}
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
@Override
double area() {
return width * height;
}
}
// Usage
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
// Abstract class
abstract class Employee {
String name;
Employee(String name) {
this.name = name;
}
// Abstract method
abstract double calculateSalary();
// Concrete method
void display() {
System.out.println("Employee Name: " + name);
}
}
@Override
double calculateSalary() {
return monthlySalary * 12; // Annual salary
}
}
@Override
double calculateSalary() {
return hourlyWage * hoursWorked; // Total earnings
}
}
// Usage
public class Main {
public static void main(String[] args) {
Employee fullTime = new FullTimeEmployee("Alice", 3000);
Employee partTime = new PartTimeEmployee("Bob", 20, 80);
fullTime.display();
System.out.println("Annual Salary: " +
fullTime.calculateSalary()); // Output: Annual Salary: 36000.0
partTime.display();
System.out.println("Total Earnings: " +
partTime.calculateSalary()); // Output: Total Earnings: 1600.0
}
}
// Abstract class
abstract class Animal {
abstract void sound(); // Abstract method
// Final method
final void info() {
System.out.println("Animals are living beings.");
}
}
// Subclass
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows!");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Animal myCat = new Cat();
myCat.sound(); // Output: Cat meows!
myCat.info(); // Output: Animals are living beings.
}
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
@Override
public double area() {
return width * height;
}
}
class Parent {
void display() {
System.out.println("Parent");
void display() {
System.out.println("Child");
obj.display();
A) Parent
B) Child
C) Compilation Error
D) Runtime Error
Answer: B) Child
Which of the following is an example of polymorphism in
Java?
A) Method Overloading
B) Method Overriding
C) Both A and B
D) None of the above
Answer: C) Both A and B
class Test {
void display(int a) {
void display(double b) {
test.display(10); // Line A
test.display(10.5); // Line B
A) Integer: 10
Double: 10.5
B) Compilation Error
C) Integer: 10
Double: 10
D) Integer: 10
Double: 10.0
Answer: A) Integer: 10
Double: 10.5
interface Animal {
void sound();
System.out.println("Dog barks!");
myDog.sound();
A) Dog barks!
B) Compilation Error
C) Runtime Error
D) No output
Answer: A) Dog barks!
class Base {
void show() {
System.out.println("Base class");
}
void show() {
System.out.println("Derived class");
obj.show();
A) Base class
B) Derived class
C) Compilation Error
D) Runtime Error
Answer: B) Derived class
class Engine {
class Car {
Car(Engine engine) {
this.engine = engine;
A) Aggregation
B) Composition
C) Inheritance
D) Polymorphism
Answer: B) Composition
interface Shape {
void draw();
System.out.println("Drawing Circle");
System.out.println("Drawing Square");
shape1.draw();
shape2.draw();
A) Drawing Circle
Drawing Square
B) Compilation Error
C) Drawing Circle
Circle
D) Drawing Square
Square
Answer: A) Drawing Circle
Drawing Square
class Animal {
void eat() {
System.out.println("Animal eats");
void bark() {
System.out.println("Dog barks");
A) Animal eats
B) Dog barks
C) Compilation Error
D) Runtime Error
Answer: A) Animal eats