Object Oriented Features

Abstraction:
Abstraction in Java or Object oriented programming is a way to segregate implementation from interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class and Object. Abstraction in Java is achieved by using interface and abstract class in Java. An interface or abstract class is something which is not concrete , something which is incomplete. In order to use interface or abstract class we need to extend and implement abstract method with concrete behavior. One example of Abstraction is creating interface to denote common behavior without specifying any details about how that behavior works e.g. You create an interface called Server which has start(. and stop(. method. This is called abstraction of Server because every server should have way to start and stop and details may differ.
An abstract class is something which is incomplete and you can not create instance of abstract class. If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class or interface it has implemented or extended. By the way Java has concept of abstract classes, abstract method but a variable can not be abstract in Java. Popular example of abstract class in Java is ActionListener which has abstract method called actionPerformed(ActionEvent ae.. This method is called when an ActionEvent is fired like when you click on JButton. Its common in java to attach ActionListener with JButton by implementing abstract method actionPerformed(ActionEvent ae. using Anonymous class.
Example when I am creating a class called Vehicle, I know there should be methods like start(. and Stop(. but don't know start and stop mechanism of every vehicle since they could have different start and stop mechanism
Abstraction Features:
1. Use abstraction if you know something needs to be in class but implementation of that varies.
2. In Java you can not create instance of abstract class , its compiler error.
3. abstract is a keyword in java.
4. a class automatically becomes abstract class when any of its method declared as abstract.
5. abstract method doesn't have method body.
6. variable can not be made abstract , its only behavior or methods which would be abstract.
7. If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be a concrete class. alternatively this class can also be abstract.
8. Functionality hide complexity.
9. Abstraction implements through abstract class and interface.
10. If any class has any abstract method then it can not be instantiated.
11. Abstract method can not be used in normal class ,but used in abstract class.
12. Abstract class may have abstract functions.
13. Any child class has to override all the abstract class's abstract function othrwise child has to become abstract.
14. We never call the abstract function explicitly.automatically runs the code of the abstract function.
15. It is not mandatory that abstract class should have atleast one abstract function.
16. Cant mark class as abstract and final both ....both have opposite meaning.
Example: -
abstract class Base
{
int x,y;
void show()
{
System.out.println("x");
System.out.println("y");
}
abstract void display();
}
class child extends Base
{
void set (int x,int y)
{
this.x=x;
this.y=y;
System.out.println("x "+x);
System.out.println("y "+y);
}
void display()
{
System.out.println("revoke");
}
public static void main(String args[])
{
child c1= new child();
c1.set(10,20);
c1.show();
c1.display();
}
}
C:\java>javac child.java
C:\java>java child
x 10
y 20
x
y
revoke
Encapsulation:
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("Anuj");
encap.setAge(38);
encap.setIdNum("2-GA-27 manu marg housing board alwar");
System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge()+ " Addres : "+ encap.getIdNum());
}
}
Output: -
C:\java>javac RunEncap.java
C:\java>java RunEncap
Name : Anuj Age : 38 Addres : 2-GA-27 manu marg housing board alwar
Benefits of Encapsulation:
1 The fields of a class can be made read-only or write-only.
2 A class can have total control over what is stored in its fields.
3 The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.
Polymorphism and Overloading
Method Overloading: - If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly.Method overloading increases the readability of the program.
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
3. Sequence of Data type of parameters.
1. By changing number of arguments: - we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Output:30
40
2. By changing the data type: - We have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Output:21.0
40
3. Sequence of Data type of parameters.
class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Output:
I’m the first definition of method disp
I’m the second definition of method disp
Here method disp() is overloaded based on sequence of data type of parameters – Both the method have different sequence of data type of parameters.
Method Overloading and TypePromotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by the figure given below:

Example: -
class Calculation{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Output:40
60
Method overriding
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class.The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. Some languages allow a programmer to prevent a method from being overridden.
Example:-
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
This would produce the following result:
Animals can move
Dogs can walk and run
Rules for method overriding: -
* The argument list should be exactly the same as that of the overridden method.
* The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
* The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.
* Instance methods can be overridden only if they are inherited by the subclass.
* A method declared final cannot be overridden.
* A method declared static cannot be overridden but can be re-declared.
* If a method cannot be inherited, then it cannot be overridden.
* A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
* A subclass in a different package can only override the non-final methods declared public or protected.
* An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
* Constructors cannot be overridden.
Using the super keyword:: -
When invoking a superclass version of an overridden method the super keyword is used.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}
}
This would produce the following result:
Animals can move
Dogs can walk and run
Polymorphism: -
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.
A simple example of polymorphism is found in the steering wheel of an automobile. The steering wheel (i.e., the interface) is the same no matter what type of actual steering mechanism is used. That is, the steering wheel works the same whether your car has manual steering, power steering, or rack-and-pinion steering. Therefore, once you know how to operate the steering wheel, you can drive any type of car.
Polymorphism means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. In a nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code (i.e. getTotArea() in the sample code shown below) that uses the polymorphic classes or interfaces. When you send a message to an object even though you don’t know what specific type it is, and the right thing happens, that’s called polymorphism. The process used by object-oriented programming languages to implement polymorphism is called dynamic binding.
There are two types of polymorphism in java- Runtime polymorhism( Dynamic polymorphism) and Compile time polymorphism (static polymorphism).
1 Compile time polymorphism (static polymorphism): - static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters.
At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile time polymorphism or static binding. The concept will be clear from the following example:
class X
{
void methodA(int num)
{ System.out.println ("methodA:" + num);
}
void methodA(int num1, int num2)
{
System.out.println ("methodA:" + num1 + "," + num2);
}
double methodA(double num) {
System.out.println("methodA:" + num);
return num;
}
}
class Y
{
public static void main (String args [])
{
X Obj = new X();
double result;
Obj.methodA(20);
Obj.methodA(20, 30);
result = Obj.methodA(5.5);
System.out.println("Answer is:" + result);
}
}
Output:
methodA:20
methodA:20,30
methodA:5.5
Answer is:5.5
As you can see in the above example that the class has three variance of methodA or we can say methodA is polymorphic in nature since it is having three different forms. In such scenario, compiler is able to figure out the method call at compile-time that’s the reason it is known as compile time polymorphism.
2 Runtime polymorhism( Dynamic polymorphism) : -Run time Polymorphism also known as method overriding. In this Mechanism by which a call to an overridden function is resolved at a Run-Time (not at Compile-time) if a base Class contains a method that is overridden. Method overriding means having two or more methods with the same name, same signature but with different implementation. In this process, an overridden method is called through the reference variable of a superclass, the determination of the method to be called is based on the object being referred to by reference variable.
Example: -
public class X
{
public void methodA() //Base class method
{
System.out.println ("hello, I'm methodA of class X");
}
}
public class Y extends X
{
public void methodA() //Derived Class method
{
System.out.println ("hello, I'm methodA of class Y");
}
}
public class Z
{
public static void main (String args []) {
X obj1 = new X(); // Reference and object X
X obj2 = new Y(); // X reference but Y object
obj1.methodA();
obj2.methodA();
}
}
Output:
hello, I'm methodA of class X
hello, I'm methodA of class Y
Method overloading and overriding both can be done in Static and dynamic polymorphism.
* It all depends on when the right method selection is being done. i.e., it depends on the type of method we use for overloading and overriding.
* Method overloading and overriding using Instance methods come under runtime/dynamic polymorphism
* Method overloading and overriding using static/private/final methods come under compile time/static polymorphism
* Please remember overriding is not possible using private and final methods.
Understanding difference between Static & Dynamic Polymorphism
Static polymorphism:memory allocated at compile time is called as static allocation.java resolves calls to overloading methods at compile time is called as Static polymorphism.
Dynamic polymorphism:memory allocated at run time is called as dynamic allocationjava resolves calls to overloading methods at run time is called as Dynamic polymorphism or Dynamic binding or Dynamic dispatch.This principle is used to create reference variable.
Static polymorphism is used the concept of early binding or we can say compile time binding where as dynamic polymorphism used the concept of late binding or run time binding.
In static polymorphism is exhibited at compilation time, where as dynamic exhibited at runtime.


Free Web Hosting