Introduction to Programming : Java & SpringBoot
  • Table of Contents
  • Introduction to Programming
  • Algorithms and logic
  • Data types and variables
  • Input and output
  • Conditional Statements
  • Loops
  • Functions
  • Arrays and strings
  • Pointers and references
  • Introduction to Object-Oriented Programming (OOP)
    • Demonstrate OOPS Concept
  • File handling
  • Introduction to Spring Boot
  • Core Concepts and Dependency Injection
  • Building Web Applications with Spring Boot
  • Spring MVC and Web Development
  • Database Integration with Spring Data
  • Building RESTful APIs with Spring Boot
  • Securing Spring Boot Applications with Spring Security
  • Advanced Topics in Spring Boot
  • Testing and Deployment
  • Real-world Projects
Powered by GitBook
On this page
  1. Introduction to Object-Oriented Programming (OOP)

Demonstrate OOPS Concept

here's an example Java program that demonstrates the use of all the OOP concepts:

Animal.java
public abstract class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public abstract String getSound();
}
Dog.java
public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    
    public String getSound() {
        return "Woof!";
    }
}
Cat.java
public class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
    
    public String getSound() {
        return "Meow!";
    }
}
AnimalSound.java
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).

PreviousIntroduction to Object-Oriented Programming (OOP)NextFile handling

Last updated 2 years ago