0% found this document useful (0 votes)
6 views

OOP Example

Uploaded by

haseeb safdar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

OOP Example

Uploaded by

haseeb safdar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

// Interfaces

interface Animal {
void eat();
void sleep();
void makeSound();
}

// Abstract class for Mammals


abstract class Mammal implements Animal {
protected String name;
protected int age;

public Mammal(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public void sleep() {
System.out.println(name + " is sleeping");
}
}

// Abstract class for Birds


abstract class Bird implements Animal {
protected String name;
protected int age;

public Bird(String name, int age) {


this.name = name;
this.age = age;
}
}

// Concrete classes for specific animals


class Cow extends Mammal {
public Cow(String name, int age) {
super(name, age);
}

@Override
public void eat() {
System.out.println(name + " is grazing");
}

@Override
public void makeSound() {
System.out.println(name + " says moo");
}
}

class Lion extends Mammal {


public Lion(String name, int age) {
super(name, age);
}

@Override
public void eat() {
System.out.println(name + " is hunting");
}

@Override
public void makeSound() {
System.out.println(name + " roars loudly");
}
}

class Parrot extends Bird {


public Parrot(String name, int age) {
super(name, age);
}

@Override
public void eat() {
System.out.println(name + " is eating seeds");
}

@Override
public void makeSound() {
System.out.println(name + " mimics human speech");
}
}

class Elephant extends Mammal {


public Elephant(String name, int age) {
super(name, age);
}

@Override
public void eat() {
System.out.println(name + " is eating leaves");
}

@Override
public void makeSound() {
System.out.println(name + " trumpets loudly");
}
}

public class Zoo {


public static void main(String[] args) {
Cow cow = new Cow("Betsy", 5);
Lion lion = new Lion("Simba", 7);
Parrot parrot = new Parrot("Polly", 3);
Elephant elephant = new Elephant("Dumbo", 10);

cow.eat();
cow.sleep();
cow.makeSound();

lion.eat();
lion.sleep();
lion.makeSound();

parrot.eat();
parrot.sleep();
parrot.makeSound();

elephant.eat();
elephant.sleep();
elephant.makeSound();
}
}

You might also like