Abstraction:
Sometimes we need not to use super class or we want that some particular method must be defined in the sub class then we use abstract classes and methods. In abstract class, we have to leave atleast one incomplete method. This method is called abstract and defined by writing abstract before method.
- package flowkl;
- //defining abstract class
- abstract class AbsClass
- {
- // abstract method, no body for this method
- public abstract void method();
- }
- class SubClass extends AbsClass
- {
- // Definition of abstract method in sub class
- // body is here
- public void method()
- {
- System.out.println("method is completed by sub class");
- }
- }
- public class Tutorials
- {
- public static void main(String args[])
- {
- //object of sub class
- SubClass object = new SubClass();
- object.method();
- }
- }
Properties of abstraction:
- Class is defined with keyword abstract.
- At least one method must be abstract. Abstract method is defined by starting with keyword abstract and removing body. Abstract method is end with semicolon.
- Abstract method can be defined only in abstract class.
- An abstract class may or may not has any abstract method.
- Sub class must define that method, otherwise sub class must also be an abstract class.
- We can not make any object of an abstract class, i.e. we can not use it. An abstract class can only be extended.
Polymorphism:
I will start with two sentences:
- Car has four wheels.
- Car is a four wheeler.
Till now we have called classes by creating objects. Class (which is calling) has those objects of other classes. It is called 'has-a' relationship. But in inheritance we used to inherit properties of other class directly. Sub class has not super class, but sub class is itself super class. It is 'is-a' relationship. So we can call a sub class by giving reference of super class. In other words, we can say that sub class is an instance of super class.
- package flowkl;
- class FourWheeler
- {
- public void wheel()
- {
- System.out.println("I have 4 wheels");
- }
- }
- class Car extends FourWheeler
- {
- public void wheel()
- {
- System.out.println("car has four wheels");
- }
- }
- public class Tutorials
- {
- public static void main(String args[])
- {
- // object of Car class with reference of FourWheeler
- // Car is a FourWheeler
- FourWheeler obj = new Car();
- obj.wheel();
- // we can not write
- // Car obj2 = new FourWheeler();
- // we can do upper casting, not lower
- }
- }
OUTPUT:
- car has four wheels