Demonstrate OOPS Concept
here's an example Java program that demonstrates the use of all the OOP concepts:
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract String getSound();
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public String getSound() {
return "Woof!";
}
}
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
public String getSound() {
return "Meow!";
}
}
import java.util.ArrayList;
public class AnimalSound {
public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog("Buddy"));
animals.add(new Cat("Whiskers"));
for (Animal animal : animals) {
System.out.println(animal.getName() + " says " + animal.getSound());
}
}
}
This program defines an abstract class Animal
that has a private name
field and an abstract getSound
method. The Dog
and Cat
classes extend Animal
and implement getSound
to return the appropriate sound for each animal.
The AnimalSound
class creates an ArrayList
of Animal
objects, adds a Dog
and a Cat
to it, and then iterates over the list, calling getName
and getSound
on each animal and printing the results to the console. This demonstrates the use of inheritance and polymorphism in OOP.
Overall, this program showcases encapsulation (the private name
field), inheritance (the Dog
and Cat
classes extending Animal
), polymorphism (the Animal
objects being treated as either Dog
or Cat
objects depending on their actual type), and abstraction (the Animal
class being abstract and defining an abstract method that its subclasses implement).
Last updated