Share
Explore

Java Lab and Lecture: Understanding Interfaces and Abstract Classes with Inheritance


Lecture

Part 1: Introduction to Interfaces and Abstract Classes

Objective: Understand the role and use of interfaces and abstract classes to enable better OO design in Java.
Topics Covered:
What is an interface?
What is an abstract class?
Difference between interfaces and abstract classes.
When to use them in Java.

Create a Java program that demonstrates the use of abstract classes and interfaces, themed around a jungle council of animals selecting a leader.

The program will involve an abstract class `Animal`, representing the general characteristics of an animal, and an interface `CouncilMember`, representing the ability to participate in the council and cast a vote for a leader.

### Java Program: Jungle Council
#### Part 1: Abstract Class `Animal`
abstract class Animal { protected String name;
public Animal(String name) { this.name = name; }
public String getName() { return name; }
// Abstract method abstract void makeSound(); } ```
In this part, `Animal` is an abstract class with a property `name` and an abstract method `makeSound()`.
Each specific animal will have its own implementation of `makeSound()`.
#### Part 2: Interface `CouncilMember`
```java ​interface CouncilMember { void castVote(); }
The `CouncilMember` interface contains a method `castVote()`, which will be implemented by animals that are members of the council.
#### Part 3: Specific Animal Classes
```java class Lion extends Animal implements CouncilMember { public Lion(String name) { super(name); }
@Override void makeSound() { System.out.println(name + " roars!"); }
@Override public void castVote() { System.out.println(name + " votes!"); } }
class Elephant extends Animal implements CouncilMember { public Elephant(String name) { super(name); }
@Override void makeSound() { System.out.println(name + " trumpets!"); }
@Override public void castVote() { System.out.println(name + " votes!"); } } ```
In this part, `Lion` and `Elephant` classes extend the `Animal` class and implement the `CouncilMember` interface, providing their own implementations of `makeSound()` and `castVote()`.
#### Part 4: Jungle Council Meeting
```java public class JungleCouncilMeeting { public static void main(String[] args) { Lion leo = new Lion("Leo"); Elephant ella = new Elephant("Ella");
// Animals make sounds leo.makeSound(); ella.makeSound();
// Council members casting votes leo.castVote(); ella.castVote();
// Determine the leader (simplified example) System.out.println("The council has voted. The new leader is " + leo.getName() + "!"); } } ```
In this part, a `main` method simulates a council meeting. The lion and elephant make their sounds and then cast their votes. Finally, a simple statement announces the new leader.
### Explanation
- The abstract class `Animal` provides a template for all animals, enforcing a common structure. - The interface `CouncilMember` defines behavior specific to council members, namely the ability to cast a vote. - By extending `Animal` and implementing `CouncilMember`, the `Lion` and `Elephant` classes inherit properties and methods from `Animal` and also provide specific implementations for the methods in `CouncilMember`. - The `main` method in `JungleCouncilMeeting` demonstrates polymorphism and how objects of these classes can interact.
This program effectively teaches students the concept and application of abstract classes and interfaces in Java, using a fun and engaging jungle-themed example.
Below is the complete Java code for the program illustrating the use of abstract classes and interfaces themed around a jungle council of animals. You can copy and paste this code into a text file (with a `.java` extension) to compile and run the program.
abstract class Animal { protected String name;
public Animal(String name) { this.name = name; }
public String getName() { return name; }
abstract void makeSound(); }
interface CouncilMember { void castVote(); }
class Lion extends Animal implements CouncilMember { public Lion(String name) { super(name); }
@Override void makeSound() { System.out.println(name + " roars!"); }
@Override public void castVote() { System.out.println(name + " votes!"); } }
class Elephant extends Animal implements CouncilMember { public Elephant(String name) { super(name); }
@Override void makeSound() { System.out.println(name + " trumpets!"); }
@Override public void castVote() { System.out.println(name + " votes!"); } }
public class JungleCouncilMeeting { public static void main(String[] args) { Lion leo = new Lion("Leo"); Elephant ella = new Elephant("Ella");
leo.makeSound(); ella.makeSound();
leo.castVote(); ella.castVote();
System.out.println("The council has voted. The new leader is " + leo.getName() + "!"); } } ```
Instructions to run the program:
1. Copy the code into a text file and save it with a `.java` extension, such as `JungleCouncilMeeting.java`. 2. Compile the program using a Java compiler. If you're using a command line, navigate to the directory where your file is located and run `javac JungleCouncilMeeting.java`. 3. Run the compiled program by typing `java JungleCouncilMeeting` in the command line.
This will execute the program, and you'll see the output of the animals making sounds, casting votes, and announcing the new leader.

To create a Java class hierarchy for students, where we have ComputerStudents and HealthStudents, and enforce a method called enroll through an interface, we will do the following:

Define an interface named Student.
Add an abstract method enroll in the Student interface.
Create classes ComputerStudents and HealthStudents that implement the Student interface.
Here is how the Java class hierarchy can be structured:

Interface Definition


public interface Student {
void enroll(String courseName);
}

In this interface, we define the enroll method which every student type must implement. The method takes a String parameter, representing the name of the course the student is enrolling in.

Computer Students Class


public class ComputerStudents implements Student {
@Override
public void enroll(String courseName) {
System.out.println("Computer Science Student enrolling in: " + courseName);
// Additional implementation specific to Computer Students
}
// Other methods and properties specific to Computer Students
}

The ComputerStudents class implements the Student interface and provides its own implementation of the enroll method.
This class can also have additional methods and properties that are specific to computer science students.

Health Students Class

public class HealthStudents implements Student {
@Override
public void enroll(String courseName) {
System.out.println("Health Science Student enrolling in: " + courseName);
// Additional implementation specific to Health Students
}
// Other methods and properties specific to Health Students
}

Similarly, the HealthStudents class implements the Student interface. It also provides a specific implementation of the enroll method for health science students, along with any other specific methods and properties.

Usage

public class StudentDemo {
public static void main(String[] args) {
Student computerStudent = new ComputerStudents();
Student healthStudent = new HealthStudents();

computerStudent.enroll("Advanced Programming");
healthStudent.enroll("Anatomy 101");
}
}

In the StudentDemo class, we demonstrate the usage of the ComputerStudents and HealthStudents classes. Each student type calls its own implementation of the enroll method.
This class hierarchy effectively uses an interface to enforce the implementation of the enroll method across different student types, showcasing polymorphism and the power of interfaces in Java.

Lecture on Interfaces in Contract-Based Programming

Introduction

The use of interfaces to facilitate contract-based programming.
This concept is particularly beneficial in a team environment where different parts of a software project are developed simultaneously.

Objectives

By the end of this lecture, you will be able to:
Understand what an interface is in Java.
Comprehend the concept of contract-based programming.
Recognize how interfaces enable coding to Class APIs even for classes that are yet to be written.

Part 1: What is an Interface?

Definition

An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types.
It is a way to achieve abstraction in Java, allowing you to specify what must be done but not how it's to be done.

Key Characteristics

Abstract Methods: An interface typically includes abstract methods. The classes that implement these interfaces must provide concrete implementations of these methods.
Implementing Multiple Interfaces: A Java class can implement multiple interfaces, a way to achieve multiple inheritances.
Default Methods (Java 8+): Interfaces can have default methods with a body, providing default behavior that can be overridden by implementing classes.

Part 2: Contract-Based Programming

The Concept

Contract-based programming revolves around defining clear, consistent, and reliable interfaces.
It’s like a legal contract: If you agree to the contract (implement an interface), you must adhere to all its terms (implement all the abstract methods).

Advantages

Predictability: All classes that implement an interface will have a predictable set of methods.
Maintainability: Changes to the contract don’t affect implementing classes, as long as the contract (interface) remains consistent.
Collaboration Efficiency: Different team members can work on different parts of the system without waiting for each other.

Part 3: Coding to Class APIs

Scenario Without Interfaces

Imagine you are developing a feature that relies on another class that’s yet to be written. Without interfaces, your progress might be halted.

How Interfaces Resolve This

Early Definition of APIs: Interfaces allow for the definition of APIs (the methods that will be available) early in the development process.
Parallel Development: While one team works on the implementation of the interface, another can use the interface to develop other parts of the system.
Decoupling: Interfaces lead to low coupling between different parts of a system. Teams can work independently as long as they adhere to the agreed contract.

Example

Consider an e-commerce application with a PaymentProcessor interface. Different team members can work on PayPal, Credit Card, and Bitcoin payment modules by implementing the PaymentProcessor interface. Meanwhile, another team can develop the checkout system using the PaymentProcessor interface without knowing the details of the payment implementations.

Part 4: Practical Demonstration

Live Coding Example: I'll demonstrate how to create an interface and implement it in different classes.
Exercise: You'll have the opportunity to practice by designing interfaces and implementing them.

Conclusion

Interfaces in Java are a powerful tool for contract-based programming. They provide a blueprint that can be followed by various team members, allowing for efficient parallel development and reducing dependencies. This approach leads to modular, maintainable, and scalable software architecture.

Transitivity of OBJECTS:

public class Hello {
public static void main(String[] args) {
// Initialize the Calculator object
Worker.c = new Calculator();

// Calling the static member and storing the returned value
int theAnswer = Worker.c.addNumbers(2, 2);

// Printing the result
System.out.println(theAnswer);
}
}

class Worker {
static Calculator c; // Static Calculator reference
}

class Calculator {
public int addNumbers(int a, int b) {
return a + b;
}
}

In this corrected version:
initialize Worker.c with a new Calculator instance in the main method.
The addNumbers method is called statically using Worker.c.addNumbers(2, 2), and the result is stored in theAnswer.
theAnswer is then printed to the console.

A Java program that illustrates the use of interfaces.

In this example, we'll create an interface named Animal with a method makeSound.

Then, we'll create two classes, Dog and Cat, which will implement the Animal interface and provide specific implementations for the makeSound method.

Java Program Illustrating Interfaces

// Interface definition
interface Animal {
void makeSound();
}

// Class Dog implementing the interface Animal
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof! Woof!");
}
}

// Class Cat implementing the interface Animal
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow! Meow!");
}
}

// Main class to run the program
public class InterfaceDemo {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.makeSound(); // Output: Woof! Woof!
myCat.makeSound(); // Output: Meow! Meow!
}
}

Explanation

Interface Declaration: The Animal interface is declared with an abstract method makeSound(). This method is public and abstract by default.
Implementing the Interface: The classes Dog and Cat implement the Animal interface. This means they provide concrete implementations for the makeSound method.
Method Overriding: In both Dog and Cat classes, the makeSound method is overridden to provide specific behavior for each animal type.
Creating Objects and Invoking Methods: In the main method, instances of Dog and Cat are created, typed as Animal. This demonstrates polymorphism. When we call makeSound() on these instances, the appropriate overridden method is executed.
This program is a simple yet effective illustration of how interfaces can be used in Java to enforce a contract for implementing classes, allowing for polymorphism and flexibility in design.

Interfaces in Java

Definition: An interface in Java is a (class) reference type that can contain only constants, method signatures, default methods, static methods, and nested types.
Characteristics:
Methods in an interface are implicitly abstract and public.
Interfaces cannot be instantiated.
A class implementing an interface must implement all its methods unless the class is abstract.
Example: Demonstrating a simple interface.

Abstract Classes in Java

Definition: An abstract class is a class that cannot be instantiated and can have abstract and non-abstract methods.
Characteristics:
Abstract classes can have constructors and static methods.
They can have final methods which will force the subclass not to change the body of the method.
Example: Creating an abstract class.

The use of abstract classes. In this example, we'll create an abstract class named Vehicle with an abstract method move and a concrete method fuelType. Then, we'll create two classes, Car and Bicycle, which will extend the Vehicle class and provide specific implementations for the move method.

Java Program Illustrating Abstract Classes

javaCopy code
// Abstract class definition
abstract class Vehicle {
// Abstract method
abstract void move();

// Concrete method
void fuelType() {
System.out.println("Unknown");
}
}

// Class Car extending the abstract class Vehicle
class Car extends Vehicle {
@Override
void move() {
System.out.println("Car moves on four wheels");
}

@Override
void fuelType() {
System.out.println("Petrol or Diesel");
}
}

// Class Bicycle extending the abstract class Vehicle
class Bicycle extends Vehicle {
@Override
void move() {
System.out.println("Bicycle moves on two wheels");
}

// fuelType method is not overridden, it will use the version from Vehicle class
}

// Main class to run the program
public class AbstractClassDemo {
public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBicycle = new Bicycle();

myCar.move(); // Output: Car moves on four wheels
myCar.fuelType(); // Output: Petrol or Diesel

myBicycle.move(); // Output: Bicycle moves on two wheels
myBicycle.fuelType(); // Output: Unknown
}
}

Explanation

Abstract Class Definition: The Vehicle class is defined as abstract. It contains an abstract method move() and a concrete method fuelType().
Abstract Method: The move() method is abstract, meaning it has no body in the Vehicle class. It must be overridden in any non-abstract subclass of Vehicle.
Concrete Method: The fuelType() method provides a default implementation. Subclasses can override this method to provide specific behavior.
Extending the Abstract Class: The Car and Bicycle classes extend Vehicle. They provide specific implementations of the move() method. Car also overrides the fuelType() method, while Bicycle uses the default implementation from Vehicle.
Instantiation and Method Calls: In the main method, instances of Car and Bicycle are created and their methods are called. Note that we cannot instantiate the Vehicle class directly because it is abstract.
This program demonstrates how abstract classes can be used to create a base template for other classes, enforcing certain methods to be implemented by all subclasses.

Part 2: Inheritance and Implementation

Objective: Learn how to use inheritance with interfaces and abstract classes.
Topics Covered:
Implementing an interface.
Extending an abstract class.
Method overriding.

Write a Java program that covers the topics of implementing an interface, extending an abstract class, and method overriding, focusing on inheritance and implementation.

### Java Program: Inheritance and Implementation
#### Part 1: Defining the Interface and Abstract Class
```java // Interface definition interface Shape { double area(); }
// Abstract class definition abstract class ColoredShape implements Shape { String color;
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.