college/Summer-2024/CS-3443/Slides/txt/09_Polymorphism.txt

184 lines
2.5 KiB
Plaintext
Raw Normal View History

2024-08-31 02:13:09 -05:00
Application
Programming
Hend Alkittawi
OOP Concepts
Polymorphism
POLYMORPHISM
-
Polymorphism enables you to write programs that processes
objects that share the same superclass either directly or
indirectly as if they were all objects of the superclass.
-
The polymorphism occurs when a program invokes a method
through a superclass variable, at execution time the correct
subclass version of the method is called based on the type of
reference stored in the superclass variable.
-
A program can determine the type of an object at execution
time and act on that object accordingly.
POLYMORPHISM
Animal
Fish
🐟
Frog
🐸
Bird
🐦
xy coordinates
xy coordinates
xy coordinates
move()
move()
move()
POLYMORPHISM
Quadrilatera
l
Square
Trapezoid
Parallelogram
s
color
color
color
getPerimeter()
getPerimeter()
getPerimeter()
POLYMORPHISM
SpaceObject
LaserBeam
SpaceShip
Plutonian
picture
picture
picture
draw()
draw()
draw()
public class Animal {
public class PolymorphismDemo {
private String name;
public static void main(String[] args) {
public Animal(String name) { this.name = name; }
// Animal reference but Dog object
Animal myAnimal = new Dog("Thunder", 30);
// Output: Thunder the dog barks.
myAnimal.makeSound();
public String getName() { return name; }
public void setName(String name) { this.name = name; }
// Animal reference but Cat object
myAnimal = new Cat("Whiskers", "Persian");
// Output: Whiskers the cat meows.
myAnimal.makeSound();
public void eat() { System.out.println(getName() + " eats food."); }
public void makeSound() { System.out.println("Animal makes a sound."); }
}
}
}
public class Dog extends Animal {
public class Cat extends Animal {
private int exerciseNeeds; // in min/day
private String breed;
public Dog(String name, int exerciseNeeds) {
super(name);
this.exerciseNeeds = exerciseNeeds;
}
public int getExerciseNeeds() {
return exerciseNeeds;
}
public void setExerciseNeeds(int exerciseNeeds) {
this.exerciseNeeds = exerciseNeeds;
}
@Override
public void makeSound() {
System.out.println(getName() + " the dog barks.");
}
}
public Cat(String name, String breed) {
super(name);
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed; }
@Override
public void makeSound() {
System.out.println(getName() + " the cat meows.");
}
}
CODE DEMO
-
Create classes to demo
polymorphism concepts!
DO YOU HAVE ANY
QUESTIONS?
THANK
YOU!
@
hend.alkittawi@utsa.edu
By Appointment
Online