java inherits code example
Example 1: Inheritance in java
class Animal
{
void eating()
{
System.out.println("animal eating");
}
}
class Lion extends Animal
{
void roar()
{
System.out.println("lion roaring");
}
}
public class Cub extends Lion
{
void born()
{
System.out.println("cub drinking milk");
}
public static void main(String[] args)
{
Animal obj1 = new Animal();
obj1.eating();
Lion obj2 = new Lion();
obj2.eating();
obj2.roar();
Cub obj3 = new Cub();
obj3.eating();
obj3.roar();
obj3.born();
}
}
Example 2: how to make one java class inherit from another
public class Bicycle {
public int cadence;
public int gear;
public int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
Example 3: inheritance in java
it is used to define relationship between two class,
which a child class occurs all the properties and
behaviours of a parent class.
Provides code reusability.
Ex: in my framework I have a TestBase
class which I store
all my reusable code and methods.
My test execution classes and
elements classes will extend the
TestBase in order to reuse the code.