Wednesday, February 6, 2013

Chapter 5: Overloading, Overriding, Runtime type and Object orientation.


Chapter 5: Overloading, Overriding, Runtime type and Object orientation.


Here we can understand following concepts :


  1. Data hiding
  2. Abstraction
  3. Encapsulation
  4. IS-A relationship
  5. Has-A relationship
  6. Method signature
  7. Overloading and Overriding
  8. Static control flow
  9. Instance control flow
  10. Constructor
5.1. Data hiding:
The date should not go out directly. Declare the entire variables as private.
The advantage is to avoid data corruption and achieve security.


5.2. Abstraction:
Hiding implementation details is the concept of abstraction.
Advantages are security, enhancement, maintainability and modularity.
The main advantage of abstraction is with out effecting outside world we are allow to change the internal implementation


5.3. Encapsulation:
If any class follows abstraction and data hiding that class is said to be encapsulated class.

Encapsulation = data hiding + abstraction.

Hiding the data behind the methods is the central concept of encapsulation.
We are not allowed to access date directly from outside. We should access through getter and setter methods.

Advantages are security, maintainability, modularity and enhancement


Tightly encapsulated class: A class is said to be tightly encapsulated class if and only
if all the data members must be declared as the private.

Ex:

1. class X
   {
   private int i=10; -------Compile successfully
   }
2. class Y extends X
    {
      int y=10; -------Compile time exception
    }
3. class Z
   {
      private int a=10;


      private int getA(){return a;} ----------- Compile successfully
      private void seta(){this.a=0;}
   }
4. class L
  {
    int l=10; ----------------------- Compile time exception.
  }
5. class M extends L
   {
     private int m=20; -------------- Compile time exception.
   }
6. class N extends M
   {
    private int n=30; -------------------- Compile time exception
    }

If the parent class is not tightly encapsulated no child class is tightly encapsulated.


5.4. IS-A relationship:

IS-A relationship is also known as inheritance.
extend is the keyword to implement IS-A relationship.
Ex: Animal extends Dog, then Dog is a Animal.
Advantage is reusability of the code.
Until certain level inheritance is the advantage feature once it got saturated it will create
side effects.

A--------B--------C--------D--------E--------F--------G

G g = new G()


For the above statement,
For creating instance of G, internally it will create F, E, D, C, B, A instances.
Creating instances or objects are very costly operation.




5.5. Has-A relationship:

This relationship is called as composition/aggregation
There is no separate keyword for implementing Has-A relationship.
Advantage is re usability.

class Engine
{

-----
--------
m1();
-----
-----

}


class Car
{

Engine e = new Engine(); // class Car has Engine

e.m1();

}


5.6. Method Signature:

Method signature consists of the name of the method followed by arguments (order of
the arguments also considered).
Return type is not a part of method signature in Java.
Within the class there is change of having two methods with the same signature,
violation leads to compile time exception.
Ex:
class Sample
{
public void m1(){}
public int m1() Compile time exception like method m1() already
{ defined
return 10;
}
}

5.7. Method overloading and overriding:

The methods are said to be overloaded if and only if the name of the methods are same
but with different arguments (at least order).
Overloading method resolution will take place at compile time only bases on the reference type. Hence overloading is an example of compile time polymorphism. Overloading is also called static binding or early binding.

5.8. Automatic promotion in overloading:

In the following example s.m1(‘a’); the compiler will check is there any method m1()
with char as the argument in sample class.








If there is no such method then compile automatically promotes to char to the int and it will check is there any method with int as the argument. If there is no such method it will continue the same process for the long followed by float followed by double. If still there is no such method then the compiler will rise a compile time exception saying there is no such method m1 ( ) which can take char as the argument.

In the case of method overloading our concentration is always on the method names (method names must be same) and arguments(must be different, at least order). We never consider return type, access specifier and throws class in the overloading.



Observe the following cases.

Case1:

class A
{
public void m1(Object o)
{
System.out.println(“Object version”);
}
public void m1(String s)
{
System.out.println(“String version”);
}
}
class Sample extends A
{
public static void main(String args[])
{
Sample s = new Sample(); Output
s.m1(null); ---------------------------------------------- String version
}
}

Case 2:

class A
{
public void m1(int i, float f)
{
System.out.println(“int ,float”);
}
public void m1(float f, int i)
{
System.out.println(“float, int”);
}
}
class Sample extends A
{
public static void main(String args[])
{
Sample s = new Sample();
s.m1(10,10.1f); -------------------------Compile successfully
s.m1(10.2f,10); -------------------------Compile successfully
s.m1(10,10); ----------Compile time exception saying reference to m1 is ambiguous
}
}


Case 3:

class Animal
{}
class Monkey extends Animal
{}
class A
{
Public void m1(Animal a)
{
System.out.println(“Animal version”);
}
Public void m1(Monkey m)
{
System.out.println(“Monkey version”);
}
}
class Sample extends A
{
public static void main(String args[])
{
Sample s = new Sample();
s.m1(null); ----------------------------Monkey version
Monkey m = new Monkey();
s.m1(m); -----------------------Monkey version ( if Monkey version is not there
then the out put is Animal version)
Animal a = new Animal();
s.m1(a); -------------------------Animal version
Animal am = new Monkey();
s.ma(am); -------------------------Animal version
}
}
Overloaded methods will resolve at compile time only based on references. We never
consider runtime objects in overloading.


5.9. Method Overriding:
Two methods are said to be overridden if and only if their signatures must be same.
5.9.1. Rules for overriding:
Name of the methods must be same .
Arguments must be the same including order.
Signatures must be same
Return types must be same until 1.4 versions. But in 1.5 versions covariant return types are also allowed.
Final methods cannot be overridden in the child class.
Overriding concept can not apply for private methods. If we want same method name we declare in child class but that is not considered as overridden.


Ex:
class Trailp
{
private void m1()
{
System.out.println(“This is parent tail method”);
}
}
class Trailc extends Trailp
{
private void m1()
{
System.out.println(“This is child trail method”);
}
public static void main(String args[])
{
System.out.println(“This is main method”);
Trailc tc = new Trailc();
tc.m1();
}
}
While overriding decreasing the access specifier is not allowed, violation leads to compile
time exception.
Ex:
class Trailp
{
public void m1()
{
System.out.println(“This is parent tail method”);
}
}
class Trailc extends Trailp
{
private void m1() ------------Compile time exception ( while overriding decreasing the
{ access specifier is not allowed)
System.out.println(“This is child trail method”);
}
public static void main(String args[])
{
System.out.println(“This is main method”);
Trailc tc = new Trailc();
tc.m1();
}
}



5.10. Access specifier priority:















    Thursday, March 29, 2012

    Chapter 4: Declarations and Access control

    Chapter 4: Declarations and Access control

    4.1. Java source file structure:
       
                    A java program may contain any number of classes but at most one class we can declare as the public.
                If there is any public class the name of the program and the name of the public class must be matched. Otherwise compiler gives compile time exception.
               If there is no public class any class name we can use as the file name.Packages in java are encapsulation mechanism in order for resolving naming conflicts.By using package we can group related classes, interfaces into a single module.It is convention to name the packages use their internet domain in reverse.

               In any java file more than one package statement is not allowed and if we are specifying any package statement it should be the first statement in the file.





    Explicit class import is highly recommended in real time because to identify which
    classes are using in the code.
    The correct sequence of statements inside java program is
    Package statement------------almost one statement is allowed
    import--------------------------any number of statements are allowed
    class/interface---------------any number of statements are allowed

    If any class is available in two packages and we include those two packages in the
    program then compiler will show the compile time exception. To solve this type of
    problem we should go for fully qualified name.

    import statement is totally compiling time issue. More number of imports, more will be
    the compile time. There is no effect of increasing number of imports at run time.
    The order in which compiler resolves the import statements is as follows
    Explicit class imports
    Current package imports
    Implicit class imports.

    4.2. Class lever access modifiers:

             The access modifier or specifier of a class describes the complete behavior of our class.
    The only allowed modifiers for the top level classes are public, default, final, abstract
    and strictfp.
    If we are using any other modifiers like private, protected, synchronized ---- we will get
    a compile time exception.
    Public class: If a classed declared as the public we are allowed to access that class
    from any where.
    Default class: If a class declared as default we can access that class only in the current
    package.
    Final class: If we are declaring a class as the final we are not allowed to create child
    class. This is for achieving security or safety. But because of using final keyword we will
    Miss one of the key benefits of object oriented programming (reusability) that is why it
    is not recommended to go for final key word unless security is not required.
    If we can declare a class as the final all the methods present in the class will
    become final. No chance of overriding instead of declaring a class as the final it is
    recommended to declare the methods as the final.
    Final class we cannot create child class. Final method we cannot override in child
    class. Final variable is constant.
    Advantage of final is safety and security.
    Disadvantage of final is reusability.
    Abstract keyword:
    Abstract is a keyword which can be applied only for methods and classes we never allow
    to use abstract keyword for the variables.
    Abstract method means the method without having any implementation. Child class is
    responsible for implementing abstract methods of the parent class.
    Abstract method can be declared as
    abstract void m1( ); [ ; is mandatory ]
    If a class declared as the abstract we are not allow creating an instance of that class.
    If a class contains at least one abstract method then we should declare the
    corresponding class as the abstract.
    An abstract class need not contain any abstract method.
    final and abstract is illegal combination for the methods and classes.
    A final class never contains any abstract method but an abstract class can contain final
    methods.
    Some illegal combinations are given below
    abstract-final
    abstract-static
    abstract-synchronized
    abstract-native
    abstract-staticstictfp
    abstract-private
    32
    Strictfp (strict floating point): This is the keyword which can be applied for the
    classes as well as methods. We cannot apply strictfp for the variables.
    Strictfp public void m1( )
    {
    System.out.println(10.0/3);
    }
    The result of floating point digits depends on OS. To reduce this declares the method as
    strictfp. If a method declared as the strictfp all the floating point calculation has to follow
    IEEE754 standards.
    If we are declaring method as the strictfp we cannot expect the result because it
    depends on the underline platform.
    Abstract and strictfp is illegal combination for the methods
    Abstract and strictfp is legal combination for classes.
    For the constructors the only allowed modifiers are public, default, private and
    protected. The remaining modifiers like static, final, abstract ---- are not allowed.

    4.3. Member access specifier:
    4.3.1. Public members:
    If a member declared as the public we are allowed to access that from anywhere. Before
    checking member visibility we should always check class visibility.
    Observe the below program:
    If class A is not defined as a public we will get compile time exception even m1() is
    public.





    4.3.2. Default members:
    If a member declared as the default with in the package only we can access
    4.3.3. Private members:
    If a member declared as the private we should access only in current class only.
    Outside the class it is not visible.
    Private methods cannot be overridden in the child class
    Private and abstract is axzillegal combination for the methods .Because private methods
    are not available in the child class for overriding (for implementing).
    4.3.4. Protected members:
    The protected members are available with the current package any where but outside
    the package only in child classes.
    Protected = default + child classes
    The protected members we can access with in the package either by using parent class
    reference or by using child class reference. But from outside the package we can access
    protected members only by using child class reference.
    Private<default<protected<public.




    In general the data members are declared as the private and the methods are declared
    as public.


    4.4. Final Variables:
    Instance variables, static variables and local variables.




    4.4.1. Final Instance variables:
    If we are not performing initialization default values will come for instance variables.
    For final instance variables we should perform initialization otherwise we will get compile
    time exception saying variable might not have been initialized.
    We will initialize the final variables
    At the time of declaration
    In the instance initialization block
    In constructor
    For final instance variable we should perform initialization before the constructor
    compiles.
    We cannot perform initialization for the final instance variables inside the methods.
    4.4.2. Final static variables:
    For the static variables no need to perform initialization. They will get default values. But
    final static variables never get default values. Before class loaded into the memory we
    should perform initialization. i.e we can perform initialization for the final static variables
    in the following places.
    At the time of declaration
    Inside static initialization block.

    4.4.3. Final Local variables:
    If we are not using even though local variable is the final no need to perform
    initialization.
    Before using a local variable we should perform initialization (either final or non final
    local variable)
    The only modifier allowed for the local variables is the final.
    We never declare any local variable with private or others.
    The variables which are declared as the formal arguments are simply acts as local
    variables of that method. The only allowed modifier for those variables is final.


    Class Sample
    {
    static void m1(final int 1, int j)
    {
    i=10 ------------ invalid
    j=20; ------------valid
    }
    Public static void main(String args[])
    {
    m1(30,300);
    }
    }
    We should not reinitialize final local variable.


    4.5. Static variables:
    The keyword static we can apply for variables, methods, classes (not for top level
    classes) and blocks.
    Static variables are class level variables in general static variables are used for defining
    constants.
    class Student
    {
    int i=10;
    static int j=20;
    public static void main(String args[])
    {
    Student s1 = new Student();
    S1.i=100;
    S2.j=2000;
    Student s2 = new Student();
    System.out.println(s2.i); --------------------10


    System.out.println(s2.j); --------------------20
    }
    }

    1. For instance variables a separate copy will create for every instance but in the case
    of static variables, a simple global copy will create and shred by all instances.
    2. We can access static variables either by object reference or by class name (be class
    name is the recommended). We can change the value of static variables by using
    object reference. In that case the changes will reflect for all the remaining instances
    that’s why in general static variables always associated with final to define constants
    so that the objects will get read access only.
    3. Static methods should have implementation but abstract methods should not have
    implementation hence static and abstract illegal combination for the methods.
    4. Static and abstract combination, we never apply for top level classes but we can
    apply for nested classes.
    5. Non-static variables cannot refer from the static context directly violation leads to
    compile time exception.
    Ex1) Consider the following declarations
    int i =10;
    static int j =20;
    public void m1()
    {
    System.out.println(i);
    }
    public static void m1()
    {
    System.out.println(i);
    }
    Ex2) which of the following are valid statements in the same class?
    (1 & 3) instance members we can access directly from instance environment
    (1 & 4) invalid because we cannot access instance members directly from the static
    members.
    (2 & 3) static members can be accessed from any where (either from instance
    environment or from static environment.
    (2 & 4) static members can be accessed from static environment.
    6. Static methods can be overloaded but cannot be overridden.


    4.6. Synchronized:
    The keyword synchronized we can apply for methods and blocks. On any objet at time
    only one thread is allowed to execute synchronized methods or synchronized blocks on a
    particular object.
    The advantage is security and data consistency
    The disadvantage is a big performance problem because of synchronized keyword.

    4.7. Native:
    Native is a keyword which can be applied only for methods.
    The purpose of introducing native methods in java is for improving performance of the
    system and for utilizing legacy systems
    The native methods are the methods which are implemented in non java lick c, c++ etc
    Native methods are also called foreign methods
    Java provides in built support for native methods by java native interface (JNI)
    Native and abstract is illegal combination for the methods.
    Native and strictfp is also illegal combination for the methods.
    We are allowed to override a native method as non native method.

    4.8. Transient:
    Transient is the keyword which can be applied only for variables.
    Transient means not to serialize while storing the stat of object to a file JVM ignores the
    value of transient variables, instead of considering original values JVM will take default
    values for the transient variables.
    We can apply transient for the static variables but there is no impact the original values
    will store into the file and we will get the same values.
    We can apply transient and final simultaneously for the variables but there is no impact
    of transient on the final variables.

    4.9. Volatile:
    Volatile is the keyword which can be applied only for variables.
    Volatile variable means its value will change frequently for achieving synchronization at
    the variable level, we can use volatile keyword.
    JVM will create a separate private copy of this variable for every thread so that we can
    prevent data inconsistency problems.
    Volatile keyword is completely outdated now a day because it will create performance
    problem.
    Volatile and final is illegal combination for the variables.

    4.10. Interfaces:
    An interface defines a contract between client and service provider. It describes
    the set of services (with out implementation details) provided by service provider to the
    client. By using interface concept we are hiding implementation details so that we can
    achieve security and we can change internal implementation with out effecting outside
    world.
    interface Sample
    {
    public void abstract m1( );
    }
    The only allowed modifiers for the interface are public, default and abstract.
    public interface Sample{ }
    abstract interface Sample{ }
    public abstract interface Sample{ }

    interface methods:
    All the interface methods are by default public and abstract. Hence the following
    declarations are equal.
    void m1();
    public void m1();
    public abstract void m1();
    abstract void m1();
    The following declarations are illegal inside an interface.
    private int m1();
    protected int m1();
    final void m1();------------------abstract-final
    strictfp void m1(); --------------abstract-strictfp
    static void m1(); ----------------abstract-static
    static void m1();
    native void m1();
    100% pure abstract class is interface
    While implementing interface methods in any class we should declare the method as
    public otherwise it gives compile time exception.
    The class which is implementing any interface must responsible for implementing all the
    methods present in that interface, otherwise the class should be declared as abstract.
    interface                                                   abstract
    All the methods must be abstract.                it may contains some concrete methods also
    Constructor concept not
    applicable for interfaces                  constructors must be present inside an abstract class
    A class can extend only on class at a time.      An interface can extend any number of interfaces at a time.
    A class can implements any number of interfaces at a time.
    All the interface variables are by default public, static and final. We are not allow to
    change the value of interface variable in the implemented class.
    Ex:
    interface abc
    {
    int i=10;
    }
    class xyz implement abc
    {
    public static void main(String args[])
    {
    i=100;
    System.out.println(i); -----------compile time exception
    }
    }

    For the interface variables we should provide implementation at the time of declaration
    only otherwise it will give compile time exception.
    We never allowed declaring interface variables as volatile or transient violation leads to
    compile time exception.
    All the following declarations are equal inside an interface.
    int i=10;
    public int i=10;
    public static int i=10;
    public static final int i=10;
    final int i=10;

    Tag interfaces: If the interface is marked for some ability such type of interfaces are
    called marker ability or interface ability or tag reference.
    Ex: serializable interface, clonable interface, comparable interface
    If the interface does not contain any method by default the interface is marker interface
    or tag reference. Even though the interface contains some methods still we can use
    marker interface, if that interface is marked for some ability.

    Case1:
    interface Left
    {
    public void m1();
    }
    interface Right
    {
    public void m1();
    }
    class Sample implements Left,Right
    {
    public void m1()
    {
    System.out.println(“Success”);
    }
    }
    If a class implements two interfaces Left and Right which contain the methods with the
    same name and arguments and same return type then only one implementation is
    enough.

    Case2:
    interface Left
    {
    public void m1();
    }
    interface Right
    {public void m1(int i);
    }
    class Sample implements Left,Right
    {
    public void m1()
    {
    System.out.println(“Success”); over loaded methods
    }
    public void m1(int i){}
    }
    If method signature is different we should provide implementation for both methods.

    Case3:
    interface Left
    {
    public void m1();
    }
    interface Right
    {
    public void m1(int i);
    }
    class Sample implements Left,Right
    {
    int i;
    public void m1()
    {
    System.out.println(“success”); overloaded methods
    }
    public int m1(int i)
    {
    System.out.println(i);
    Return I;
    }
    }
    If method signature is different we should provide implementation for both methods.

    Case 4:
    interface Left
    {
    public void m1();
    }
    interface Right
    {
    public int m1();
    }

    class Sample implements Left,Right
    {
    int i;
    public void m1()
    {
    System.out.println(“Success”);
    } Compile time exception
    public int m1()
    {
    System.out.println(i);
    Return i;
    }
    }
    If both interfaces contain method with same signature but different return types, we are
    not allowed to implement two interfaces simultaneously in the same class.


















    Wednesday, February 15, 2012

    Chapter -3 Flow Control

                                           Chapter -3 Flow Control

    Flow control describes the run time order in which the statements are going to execute.


                                              Flow control

    Selection stmts               Iterative stmts                   Transfer stmts
    EX:                                 Ex:                                      Ex:
    If                                     For                                     break
    If else                            While                                    continue
    Switch                           do while                                return
                                                                                      Try, catch, finally
                                                                                      Assertion


    3.1. Selection statements





    3.1.1. if else:
    The else part and curly braces are optional
    The valid argument for if statement is Boolean only.
    With out curly braces under if only one statement is allowed but that statement never is
    declarative statement.
    The compiler always map the else statement which is nearest if which does not have
    else already. Hence there is no dangling-else problem in java.
    3.1.2. Switch:
    The valid arguments for the switch statement are byte, char, short and int.
    Curly braces are mandatory.
    Both case and default are optional.
    All the statements inside switch must be associated with some case or default. This
    means independent statements are not allowed.
    All the case labels must be in the range of switch argument.
    All the labels must be compile time constants and it may be compile time constant
    expressions also.
    The case labels never be duplicated.
    The default statement we can place anywhere in the switch but JVM always consider the
    default after the cases only.



    int x=1;
    switch (x)
    {
    Case 1: System.out.println(“1”);
    Case 2: System.out.println(“2”);
    Case 3: System.out.println(“3”);
    break;
    default: System.out.println(“default”);
    }
    If x =2 then output is 2,3
    In execution flow if JVM finds the matched case then from that case all the statements
    will execute until end of the switch or break statement.


    3.2. Iteration Statements
    3.2.1. While( ):
    This loop is preferable if we don’t know the number of iterations in advance.
    The valid argument for the while loop is boolean.
    Curly braces are optional.
    With out curly braces only one statement is allowed but that statement never be
    declarative.
    final int x = 10;
    while(x>15)
    {
    System.out.println(“hi”);
    }
    System.out.println(“Hello”);
    This program will give compile time exception. Because unreachable statement.
    3.2.2. Do While( ):
    If we want to execute the loop body at least one time then we will go for do while( )
    loop.
    Curly braces are optional.
    With out curly braces only one statement is allowed that statement never be declarative.
    With out curly braces we should keep exactly one statement at least empty statement.
    If the argument is compile time constant true then the statement after do while will
    become unreachable statements.

    3.2.3. for( ):
    Curly braces are optional.
    With out curly braces only one statement is allowed that statement never be declarative.
    for(initialization;condition;incre/decrement)
    Initialization section:
    In initialization section we are not allowed to declare variables of different types.
    For(int a= 10, byte b=20; ; ;) this is invalid.
    We are allowed to declare the variables of some type but the type we should specify
    only on time.
    for(int i=0,int j=1; ; ;) is invalid.
    for(int i=0,j=1; ; ;) is valid.
    In the initialization part we are allowed to take any java statement including
    System.out.println( ) also.
    Conditional expression:
    The conditional expression is optional. The default value is true.
    The conditional expression is any java statement but it should return boolean.
    All the three parts of for loop is optional.
    for( ; ; ) is valid in java.
    Break and Continue:
    Break statement we can use
    Inside loops (to break the loop)
    inside switch statement (to come out from the switch)
    inside labeled blocks (to come out from the block)
    If we are using break anywhere else we will get a compile time exception saying break
    outside switch or loop
    Continue statement we should use only in the loops. If we are using anywhere else we
    will get a compile time exception saying continue outside loop.