Exp 2.1 Java
Exp 2.1 Java
Experiment: 2.1
AIM: Consider the Animal class that has only one method, walk(). Next, we want to create a
derived class called Bird from Animal class that has a fly() method.Finally, we can create a
Bird object that can call both fly() and walk(). You must add a sing method to the Bird class,
then modify the main method accordingly so as to get the desired output.
Algorithm/Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
//Type of inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal
{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark(); //Compile Time Error
}
}
Program Code:
class Animal{
void walk()
System.out.println("I am walking");
}
class Bird extends Animal
{
void fly()
System.out.println("I am flying");
void sing()
System.out.println("I am singing");
}
public class Solution
{
public static void main(String[] args) {
Bird bird = new Bird();
bird.walk();
bird.fly();
bird.sing();
}
}
Output:
Learning outcomes:
1. How to inherit in java
2. How to extends the class