SE322 TutorialOnChapter5
SE322 TutorialOnChapter5
Abstract Classes
Interfaces
Polymorphism
Dynamic Binding
Concrete classes and methods
interface Walkable {
void walk();
Polymorphism
Definition: The ability for different classes to be treated as instances of the same class
through inheritance.
Dynamic Binding
Definition: The ability of the program to resolve which method to invoke at runtime
rather than compile-time.
@Override
public void walk() {
System.out.println("Cat is walking...");
}
}
Concrete Method:
A concrete method is a method that has a complete implementation. In contrast to
abstract methods (which only have a method signature without a body), concrete methods
provide a specific set of instructions that are executed when the method is called.
Concrete methods can exist in both abstract classes and concrete classes.
All methods in an interface are abstract (non-concrete, have no implementation)
Polymorphism is the broader concept that allows objects of different types to be treated as if they
are objects of the same type. Dynamic binding (for runtime polymorphism) ensures that the
correct method associated with the actual object type is called when there are overridden
methods.
3. Exercises
1. Implementing New Animals:
Create a new class Dog that extends Animal and implements Walkable.
The sound method should output "Bark!".
The walk method should output "Dog is walking...".
2. Bird Interface:
Design an interface named Flyable with a method named fly.
Implement this interface in a new class called Bird. The fly method should print
"Bird is flying...".
Make sure the Bird class also extends the Animal class and implements its
methods.
3. Animal Array:
Create a class TestAnimals that will have a main method to test what you have
done so far.
Create an array of Animal and populate it with instances of Horse, Cat, and Dog.
Loop through the array and call the sound method on each animal.
Extend the loop to also call the walk method if the animal is an instance of
Walkable.
4. Dynamic Binding:
Create a method that takes an Animal reference as its parameter.
Inside this method, use dynamic binding to check if the animal can walk (i.e., if
it's an instance of Walkable) and, if so, call its walk method.
Test this method with different animal objects.
5. Extending Interfaces:
Create a new interface Runnable with a method run.
Modify the Dog class to implement both Walkable and Runnable.
Implement the run method to print "Dog is running...".
Test the Dog class by creating an instance and calling all its methods.