Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

Thursday, June 2, 2011

Oops Concepts - Polymorphism

Polymorphism

This refers to the ability to assume different forms. In OOP, it indicates a language’s ability to handle objects differently based on their runtime type.
When objects communicate with one another, we say that they send and receive messages. The advantage of polymorphism is that the sender of a message doesn’t need to know which class the receiver is a member of. It can be any arbitrary class. The sending object only needs to be aware that the receiving object can perform a particular behavior.

A classic example of polymorphism can be demonstrated with geometric shapes. Suppose we have a Triangle, a Square, and a Circle. Each class is a Shape and each has a method named Draw that is responsible for rendering the Shape to the screen.

With polymorphism, you can write a method that takes a Shape object or an array of Shape objects as a parameter (as opposed to a specific kind of Shape). We can pass Triangles, Circles, and Squares to these methods without any problems, because referring to a class through its parent is perfectly legal. In this instance, the receiver is
only aware that it is getting a Shape that has a method named Draw, but it is ignorant of the specific kind of Shape. If the Shape were a Triangle, then Triangle’s version of Draw would be called. If it were a Square, then Square’s version would be called, and so on.

We can illustrate this concept with a simple example. Suppose we are working on a small graphics package and we need to draw several shapes on the screen at one time. To implement this functionality, we create a class called Scene. Scene has a method named Render that takes an array of Shape objects as a parameter. We can now create an array of different kinds of shapes and pass it to the Render method. Render can iterate through the array and call Draw for each element of the array, and the appropriate version of Draw will be called. Render has no idea what specific kind of Shape it is dealing with.

The big advantage to this implementation of the Scene class and its Render method is that two months from now, when you want toadd an Ellipse class to your graphics package, you don’t have to touch one line of code in the Scene class. The Render method can draw an Ellipse just like any other Shape because it deals with them generically. In this way, the Shape and Scene classes are loosely coupled, which is something you should strive for in a good object-oriented design.

This type of polymorphism is called parametric polymorphism , or generics. Another type of polymorphism is called overloading. Overloading occurs when an object has two or more behaviors that have the same name. The methods are distinguished only by the messages they receive (that is, by the parameters of the method). Polymorphism is a very powerful concept that allows the design of amazingly flexible
Applications.

OOPS Concept-Constructors


Constructors 
The purpose of Constructor is to perform of our creted object. Whenever we are calling new operator for the creation of object, it calls constructor automatically to provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}

Rules Of Constructor :

1. Constructor concept is applicable for every class including abstract class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be same.
4. The allowed modifiers for the constructors are public, private, protected, and default. If you are applying any other we will get a CTE saying “modifier xxx not allowed her”.
5. We can’t give return type for the constructor even void also.

If we will give return type for the constructor that thing as a method instead of constructor that thing as a method instead of constructor (so,there is no CTE). Ie., it is legal (but stupid) to have a method whose name same as classname.

Default Constructor:-

If the programmer is not writing any constructor, then only compiler will generate a default constructor.
Ie., either programmer written constructor or compiler generated must present in your class but not both at a time.
Prototype of default constructor shown below:

a).Programmer written code:-

Compiler generated code:-
class Test
{
Test()
{
super();
}
}
  • The default constructor is always no argument constructor.
  • The access modifier of the default constructor is sane as access modifier of the class (public & default only).
  • The default constructor contains only one statement which is ‘no arg call to super class Constructor ‘ (super();)
b) Programmer written code:-
class Test {
Test(int i)
{
System.out.println(“constructor”);
}
}

Compiler generated code:-

class Test {
Test(int i)
{
super();
System.out.println(“constructor”);
} }

c). Programmer written code:-

class Test {
Test(int i)
{
super();
System.out.println(“Hai”);
} }
Compiler generated code:- no new code is going to generate.

d). Programmer written code:-

class Test {
void Test()
{
System.out.println(“hello”);
}
}

Compiler generated code:-

class Test {
void Test()
{
System.out.println(“hello”);
}
Test()
{
super();
}
}

e). Programmer written code:-

class Test {
Test()
{
this(10);
System.out.println(“hai”);
}
Test(int i)
{
System.out.println(i);
}
}

Compiler generated code:-

class Test {
Test() {
this(10);
System.out.println(“hai”);
}
Test(int i) {
super();
System.out.println(i);
}
}
  • The first line inside a constructor must be a call to super class constructor ( by using super();) or a call to overload constructor of the same class. (by using ‘this’ keyword).
  • If you are not writing the first line as either ‘super()’ or ‘this’ then compiler will always keep a no arg call to super class constructor (super();).
1. Allowed only in Constructors.
2. Must be first statements.
3.Either super() or this, but not both.
  • We can invoke another constructor from constructor from a method violation leads to CTE. i.e, super() or this must be used inside the constructor only not anywhere else.
Overloaded Constructors:

We are allowed to keep more than one constructor inside a class , which are considered as overloaded constructors. We can’t override the constructors, because they belong to the same Ex: class Test {
Test(int i){}
Test(){} ---->Overloaded Constructors
}
  • Constructors are not inherited and hence we are not allowed to override a constructor.
  • while recursive method invocation we will get stackoverflowException But in case of constructors we will get compile time error.
  • If we are writing any constructor in our class it is recommended to place default constructor also. Otherwise we should take care while writing the constructor child case.
  • If the parent class constructor throws some Checked Exception, while writing child class constructors we should take care.In case of unchecked exception no rule.
Recursive Constructor invocation:

class Sample {
Sample() // This is a compile time problem
{
this(10);
}
Sample(int i)
{
this(); // Invalid, CTE: recursive constructor invocation
}
public static void main(String a[])
{
System.out.println(“hai”);
}
}
Constructing the Child class constructors:

Example:
class P {
P()
{ super(); }
}
class C extends P
{
C() {
super();
} } //valid

Example:
class P {
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}

Example: class P
{
P() throws Exception ----> checked exception
{ }
}
class C extends P
{
C() // compile time error unhandled exception type exception
{ }
}

Wednesday, June 1, 2011

OOPS Concept-Method Hiding


Method Hiding:-

This is exactly same as overriding except both parent & child class methods must be declared as static. In the method hiding the method resolution take care by compiler only based on the reference type.
Ex:
class P
{
static int x=10;
int y=20;
}
class C extends P
{
static int x=100;
int y=200;
}
class Sample
{
public static void main(String[] a)
{
P p=new C();
System.out.println(p.x+”,”+p.y); //10,20
C c=new C();
System.out.println(c.x+”,”+c.y); //100,200
P p1=new P();
System.out.println(p1.x+”,”+p1.y); //10,20
}
}
  • We can’t override in the child class. But if define exactly same variable in child class.
  • Variable resolutions take care by compiler only based on the reference type.

Tuesday, May 31, 2011

OOPS Concept-Method Overriding


Method Overriding 
If you don’t want parent class implementation for any method we can override in the child class based on our child class requirement. This concept is called Overriding.
While overriding we have to fallow rules:
1. In the overriding, the method names and arg’s must be same.
Ie. In the case of the overriding the signatures of the methods must be same
Until 1.4 version, the return types must be same. But from 1.5 version onwards covariant return types are also allowed.
Example:
class p { public Number getNumber(){} }
class c extends P{ public Number getNumber(){} }
(or)
class C extends P
{
public Byte/Short/Integer getNumber(){}
}
  • For Number class Byte/Short/Integer is co-variant return types or classes.
  • Hence in case of overriding as the return type we can keep child class objects also.
Example:
import java.io.*;
class P
{
public object m1(){ return new object; }
}
class C extends P
{
public Object m1(){ return new Object; }
}
class C extends P
{
public String m1(){ return “durga”; }
}//in 1.4 CTE saying m1() in C cannot override found:string, req:object: in 1.5 ver no CTE

2. final methods can’t be overridden.
3. private methods never participate in the in the overriding because these methods are not visible in the child classes.
4. While overriding decreasing access specifier is not allowed. Violation leads to CTE.

class P { public int m1(){} }
class C extends P { public int m1(){} }
Parent class -------------------------------- Child class
public ----------------------------------------------- public
protected ---------------------------------------- protected, public
default ---------------------------------------- default, protected ,public
private ---------------------------------------- private, default, protected, public

* While implementing any interface method, we should declare that method as public in the implemented class.(by default implements interface method is public and abstract)
* An abstract method can be overridden as abstract. The child of the original child class is responsible for the implementation.

class P{
public void m1()
{ } }//non abstract

abstract class C extends P{
public abstract m1(); }//valid abstract


5. While overriding the size of the CheckedException should not increase. There is no rule for UnCheckedExceptions.
Example: Base or parent class :
public void m1()throws IOException
Derived or child class :

public void m1()throws FileNotfoundException //valid

public void m1()throws Exception -->CTE

public void m1()throws RunTimeException //valid
  • We can override a synchronized method to non-synchronized and vice versa
  • We can override native to native to non native and vice versa.
  • We can override a non-final method to final method.
  • We can’t override a static method to non static and a non-static method to static violation leads to CTE .
  • While overriding method has to execute will be decided by JVM based on the Run Time Object. Hence Overriding is an example of “dynamic polymorphism” or “LateBinding” (Dynamic Method dispatch).
  • If the parent’s class reference can be used to hold child class object by using that reference we are allowed to call only parent class methods. Child class specific methods are not allowed to call by using parent class reference.