Thursday, August 6, 2009

java - Abstraction, Interfaces and Inheritance

Abstraction :

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.

Abstract class:
Use keyword abstract to declare abstract class. (public abstract class Abstractclassdemo { })

Abstract method :

If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.

If method is abstract the class should be abstract.

Ex : Abstraction is useful when extending plugin. If you need to fetch data(methods, fields) from Ad Tech plugin they will allow you to extend that plugin to use method and fields. But, they don't want to instantiate. Because, you are not going to set any values. But, they might have abstract method in their plugin. They want you to use the method child class by override the abstract method.

Interface:
Interface is useful if you want some one to force to use the methods in the child classes. You need to use implement keyword for interface. If you implement you need to use all methods declared in the interface.

Inheritance in java
Person (Parent)
  1. Employee (First Child)
  2. Owner (Second Child)

Both the child belongs to parent (Person).
Employee extends Person
Owner extends Person

1st child : When you have object you can access methods from the own Employee object. Also, you can access method from Parent object (Person)
2nd child : When you have object you can access methods from the own Owner object. Also, you can access method from Parent object (Person)

Parent : When you have Parent Object (Person) you can access only person methods (only the parent method). If you want to access child methods you need to typecast the Parent object to child object (Employee child or Owner child) whichever you want.

Note : You cannot typecast the child object to child object or child object to parent object. Only parent can typecast to any child you want.

No comments :

// Below script tag for SyntaxHighLighter