Abstract class in java
Abstract class as the name implies its an abstract.The class which is not implemented, So we cannot create the object of that class.
Abstract class contains abstract as well as non abstract methods.
we can have abstract class with out abstract method.
you can even have abstract class with final method.
if you doesnt want to implement abstract method in sub class, make the sub class as abstract.
For Example let us consider animal as our abstract class. I wrote two funtion in it
lifeSpan();
isReproduce(); Let it be always "yes".
lifeSpan(); is an abstract method , which is different for each animals
now consider sub class as dog , cat and ant
these class extends that abstract class. The relation ship will come in this way like dog is an animal, cat is a animal ..."is - a" relation ship
since the sub class extends the base class animal.. we need to define lifespan() function in each subclass.
lifespan() is different for each animal
if i create an object Animal a = new dog();
a.isReproduce() ----> "yes"
a.lifespan() -----> 13
Program
/**
* The study of behavior of animal is called ethology
*/
package com.cfed.oopsconcepts;
public abstract class Animal {
public String color;
public abstract int lifeSpan();
public void isReproduce() {
System.out.println(" YES ");
}
}
package com.cfed.oopsconcepts;
public class Dog extends Animal {
@Override
public int lifeSpan() {
// TODO Auto-generated method stub
return 13;
}
}
/**
*
*/
package com.cfed.oopsconcepts;
/**
* @author Konzern
*
*/
public class Cat extends Animal {
/* (non-Javadoc)
* @see com.cfed.oopsconcepts.Animal#lifeSpan()
*/
@Override
public int lifeSpan() {
// TODO Auto-generated method stub
return 16;
}
/**
* This method cannot access through super class
* as the method is not declared in the super class
*/
public void bark() {
System.out.println(" meow");
}
}
/**
*
*/
package com.cfed.oopsconcepts;
/**
* @author konzern
*
*/
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal animal = new Dog();
System.out.println(" Dog ");
animal.isReproduce();
System.out.println(animal.lifeSpan());
animal = new Cat();
System.out.println(" Cat ");
animal.isReproduce();
System.out.println(animal.lifeSpan());
//animal.bark();
}
}
Output
Dog
YES
13
Cat
YES
16