kirran

Wednesday, June 20, 2012

Java Object type casting

Java Object type casting

Converting object reference of one type to another type is called Java object typecasting. Casting is a programming term that means, effectively, converting a value or an object from one type to another. The result of a cast is a new value or object; casting does not change the original object or value.
The class of the object you're casting and the class you're casting it to must be related by inheritance; that is, you can cast an object only to an instance of its class's sub- or superclass-not to any random class. Casting downward in the class hierarchy is automatic, but casting upward is not.

There are two types of object typecasting:
1. upcasting 
2. downcasting


Upcasting: Upcasting is implicit and safe. Here subclass object is converted to superclass object, because a subclass object is also a superclass object.

Downcasting:Down-casting is potentially unsafe, because you could attempt to use a method that the derived class does not actually implement. With this in mind, down-casting is always explicit, that is, we are always specifying the type we are down-casting to. Converting an instance of a subclass to an instance of a superclass loses the information

Upcasting vs Downcasting

Given Below is a program which easily demonstrates the difference between Upcasting and downcastin in Java.

_____________________________________________________
Vehicle v1  = new Car();  / /Right . upcasting or implicit casting

Vehicle v2= new  Vehicle();

Car c0 = v1;  // Wrong compile time error "Type Mismatch"

  //Explicit or downcasting is required
 
Car c1 = (Car) v1 // Right. downcasting or explicit casting . v1 has a knowledge    //of Car due to line 1
 
Car c2= (Car) v2;  //Wrong Runtime exception ClassCastException because v2    //has no knowledge of Car.
 
Bus b1 = new BMW();  //Wrong compile time error "type mismatch"
 
Car c3 = new BMW(); //Right. Upcasting or implicit casting
 

Car c4 = (BMW) v1; // Wrong Runtime exception ClassCastexception
 
Object o = v1;  //v1 can only be upcast to its parent
 
Car c5 = (Car) v1; // v1 can be downcast to Car due to line 1    _____________________________________________________
  • ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance.  Use exception handling mechanism to catch ClassCastException
  • Use the instanceof operator to guard against incorrect casting.

what is encapsulation in java programming











Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. 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.

Let us look at an example that depicts encapsulation:


public 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;
   }
}
The public methods are the access points to this class.s fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.
The variables of the EncapTest class can be access as below::

/* File name : RunEncap.java */

public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("chittampally kirran");
      encap.setAge(22);
      encap.setIdNum("12343ms");
      System.out.print("Name : " + encap.getName()+
                             " Age : "+ encap.getAge());
    }
}


This would produce following result:
Name : chittampally kirran :22

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.

Wednesday, June 13, 2012

Overriding and Hiding Methods












Java-Method-Overriding-Overloading
Java Implements the Polymorphisim in one of the two ways that is Method Overriding and Method Overloading

Method Overriding :
Method overriding occurs when sub class declares a method that has the same signature (name, plus the number and the type of its parameters) and return type as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior thatfs specific to a particular subclass type. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type. Which overridden version of the method to call is decided at runtime based on the object type.

The rules for overriding a method are as follows:
  •  The argument list must exactly match that of the  overridden method. If doesn't match we will get a overloaded method not a overriding method.
  • The return type must be same as, or a subtype of, the return type declared in the original overridden method in the superclass.
  •  We can not override method marked final. Static methods can't be overridden but they can be   redefined.
  • If a method can't be inherited , you cannot override it. Overriding is nothing but we are reimplementing a method  that we are inherited
  • Overriding method must not throw checked exceptions that are new and broader than the those declared by the overridden method
  • The access level can't be more restrictive than the overridden method. It can be less restrictive than that of overridden method
  • The overriding method can throw any unchecked or runtime  exception, regardless of weather overridden method declares the exception or not.
  •  The overbidding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
  • 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.
  • Constructors cannot be overridden.

A program to explain the above rules of Java Method Overridding

public  class SuperClass{

         public void method1() {
                System.out.println("SuperClass.method1()");
         }
        
         private void method2() {
                System.out.println("SuperClass.method2()");
         }
         public final void method3(){
                System.out.println("SuperClass.method3()");
         }
          private final void method4(){
                System.out.println("SuperClass.method4()");
         }
        
         public static void method5() {
               System.out.println("SuperClass.method5()");
         }
        
         public void method6() throws Exception {
                System.out.println("SuperClass.method6()");
         }
        
         private void method7(){
                System.out.println("SuperClass.method7()");
         }
        
         private void method8(int x){
                System.out.println("SuperClass.method8()");
         }
        
         public static void method9() {
               System.out.println("SuperClass.method9()");
         }
}
public class SubClass extends SuperClass {
      
         public void method1() {
                System.out.println("OverridingClass.method1()");
         }
         private void method2(){
                System.out.println("OverridingClass.method2()");
         }
         //We can't override a public final method
         /*     public final void method3(){          
                       System.out.println("OverridingClass.method3()");
                }*/
        
         private final void method4(){
                System.out.println("OverridingClass.method4()");
         }
        
         public static void method5() {
               System.out.println("OverridingClass.method5()");
         }
        
         public void method6() throws IOException{
                System.out.println("OverridingClass.method6()");
         }
        
         public void method7(){
                       System.out.println("OverridingClass.method7()");
         }
        
         public void method8(final int x){
                System.out.println("OverridingClass.method8()");
         }
        
         //A static method cannot be overridden to be non-static instance method
         /*public void method9() {
               System.out.println("OverridingClass.method9()");
         }*/
        
}
public class MethodOverrdingSample{
       public static void main(String[] args) {
           SubClass sub = new SubClass();
           SuperClass sc = new SubClass();
           sub.method1();
           sub.method3();
           /*   Since its private, the below 2 methods are not visible
           sub.method2();
           sub.method4();*/
          
           sub.method5();
           try {
                     sub.method6();
              } catch (IOException e) {
                     e.printStackTrace();
              }
           sub.method7();
           sub.method8(100);
           sc3.method5();

          SubClass subClass = new SubClass();
         SuperClass supClass = (SuperClass)subClass;
         supClass.method5();                   
         supClass.method1();

       }
}

To invoke a superclass version of overridden method we use a super keyword. For example
            public class Superclass{
                        public void method1(){
                                    System.out.println(gSuperclass Versionh);}
                        }
            }
            public class SubClass{
                        public method1(){
                                    super.method1();       //Invoke first superclass code
                                                                        //then do the subclass specific code
                                    System.out.println(gSubclass Versionh);
                        }
            }
Method Overloading :
Method overloading means  to have two or more methods with same name  in the same class and its subclass with different arguments and optionally different return type. Which overloaded version of the method to be called is based on the reference type of the argument passed at compile time.

The rules for overloading  a method are as follows:

ðL  Overloaded methods must change the argument list.
ðL  Overloaded methods can change the return type.
ðL  Overloaded methods can declare new or broader checked exacpetions
ðL  Overloaded methods can change the access modifier.
ðL  Constructors can be overloaded.

A program to explain the above rules of Java Method Overloading

public class A {
       protected A(){
              System.out.println("Hi A Constructor");
       }
       public A(int i,int j){
              System.out.println("Hi A Constructor A,B");
       }
       public void method1(int i){
              System.out.println("Hi A in method1(i)");
       }

}
public class B extends A{
       public B(){
              System.out.println("Hi B Constructor");
       }
       public B(int i, int j){
              super(i,j);
              System.out.println("Hi B Constructor with i,j");
       }
       public void method1(int j){
              System.out.println("Hi B in method1(i)");
             
       }
       public void method1(int i, int j){
              System.out.println("Hi B in method1(i,j)");
       }
}
public class C extends A{
       public C(){
              System.out.println("Hi C Constructor");
       }
       public C(int i, int j){
              super(i,j);
              System.out.println("Hi C Constructor with i,j");
       }
       public void method1(int j){
              System.out.println("Hi C in method1(i)");
       }
      
       public void method1(int i, int j){
              System.out.println("Hi C in method1(i,j)");
       }
}
public class D {
              public  static void main(String[] args) {
              // TODO Auto-generated method stub
              int k=0;
              int l=0;
              A a=new A();
              B b= new B();
              a= b;
              C c= new C();
              A ac=c;
              a.method1(k);
              b.method1(k,l);
              b.method1(k);
              c.method1(k);
         
//Compiler erroe! Compiler looks only at the reference and sees that Class A does not have method1(int,int) method. Compiler doesn't care about the actual object at runtime
                          
       }

}

Output for the above program
Hi A Constructor
Hi A Constructor
Hi B Constructor
Hi A Constructor
Hi C Constructor
Hi B in method1(i)
Hi B in method1(i,j)
Hi B in method1(i)
Hi C in method1(i)

Instance Methods

                      An instance method in a subclass with the same signature and return type as an instance method in the superclass overrides the superclass's method.The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error.


Class Methods

If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass.

let us see the following example


public class Person {

void drive()

{

    System.out.println("we are iin person class");  }

}

class Father extends Person {

    void drive()
    {
        System.out.println("father drives smmothly yar");}
    }

class Son extends Father {

        void drive()
        {
            System.out.println("Son drives roughly yar"); }
        }

class Overridedemo extends Son {

public static void main(String[] args) {

    Person P = new Person();
    Father F = new Father();
    Father S = new Son();
    P.drive();
    P = F;
    P.drive();
    P=S;
    P.drive();
}
}