Wednesday, May 29, 2013

Interface In Java (Pure Abstract Class)



Interface:

·         Interfaces are basically used to obtain the concept of multiple inheritances in Java.
·         An interface is a construct which contain purely undefined methods or an interface is a collection of Abstract methods.
·         Syntax:
interface InterfaceName
{
            Variable declarations;
            Method declarations;
}
For example:
interface I1
{
            int x = 10; //public static final int x = 10;
            void add(); //public abstract void add();
            void sub(); //
}

  • When this interface is compiled we get an file with .class (I1.class) extension as similar from the compilation of any class.

  • By default all the variables/data members in the interface are public, final & static and all the methods are public abstract.

1)      An interface is a keyword which is used for creating or developing undefined data types.

2)      <InterfaceName> interface name represent java valid variable name which is treated as name of the interface.
Interface names are used for creating objects indirectly. i.e an object of interface can’t be created directly since it contain abstract methods.

3)      Variable declarations represent type of data members which we use as a part of interface.

4)   All the variables in the interface must be initialized. All the data members of the interface belong to the public static final XXX data members by default.

5)   Here XXX represents data-type, varName and its value. Hence all the data members of the interface are reusable general purpose data members.

6)   Method declaration represents type of methods which we use as a part of interface to perform some general purpose operation.

7)   All methods in an interface are abstract method by default, so we don’t need to use a keyword “abstract” to make them abstract. All the methods of interface are by default reusable i.e. they are “public” by default.
Note:
1)      Whenever we compile an interface we will get .class as an extension for that interface.
2)      All the interfaces are further reusable by the classes.
3)      Interfaces are not final.

Sample Program

interface Operations
{
void add();
}

class IntOperations implements Operations
{
            int a,b,c;
            void add()
            {
                        a = 10;
                        b = 20;
                        c = a+ b;
                        System.out.println (“Sum of the integers : ”, +c);
            }
};

class FloatOperations implements Operations
{
            float f1,f2,f3;
void add()
{
                        f1 = 1.25f;
                        f2 = 3.75f;
                        f3 = f1 + f2;
                        System.out.println (“Sum of floats : ”, +f3);
            }
};

class InterfaceDemo
{
            public static void main(String args[ ])
            {
                        Operations op;
                        op = new IntOperations();
                        op.add();
                       
                        op = new FloatOperations();
                        op.add();
            }
}
Hence object of the interface “Operations” will not be formed because it is abstract and if we create object of the derived class then dynamic binding fails.

Practical implementation of interfaces can be seen the working of ATM banking.
If we have HSBC ATM card, if we use SBI ATM with HSBC ATM card then money will be withdrawn on the behalf of the HSBC ATM.
And this complete operation is done through interfaces.








Classes and use of "abstract" keyword in Java



Types of classes in Java:

 There are two types of classes in Java. They are:
1)      Concrete classes
2)      Abstract classes

Concrete Class:
A class is said to be concrete class if and only if it contains fully defined methods. Fully defined methods are known as implemented or concrete methods.
Once a class is concrete than we can create object of that class directly.

class B
{
            int x,y;
            void add()
            {
                        …………
                        …………        
}
void sub()
{
                        …………
            …………
}
}

Abstract Class:
·         A class is said to be an abstract class if and only if contains some defined and some undefined methods.
·         With respect to an abstract class we can’t create an object of that class directly but we can create an object of abstract class indirectly.
·         Undefined methods in java are known as unimplemented or abstract methods.
·         An abstract method is one which does not contain any definition.
·         To make a method abstract we must use the keyword called “abstract” before the method declaration.
·         Syntax:
[access specifier] abstract returnType methodName(param, if any);
            e.g. public abstract void add(int a, int b);

·         Abstract method provides security.

NOTE: Abstract method always makes us to understand what a method can do but we can’t understand how a method can be defined.

·         A special case we have a class in which all methods are defined but we put abstract before the class to make the class secure because now we can’t create object of that class direct.

·         Once a class contains an abstract method then that class is known as an abstract class. To make a class as an abstract class we must use a keyword “abstract” before class specification.

·         Syntax of abstract class:
abstract class ClassName
{
abstract methods;
} 
·         An abstract class is one in which we have at least one abstract method.
·         Abstract classes are basically used to implement polymorphic application. To execute polymorphic application we must use dynamic binding hence abstract classes with polymorphic application along with dynamic binding improves the performance of the java program by reducing amount of memory space.

 Sample Program

abstract class Operation
{
            abstract void add();
};

class IntSum extends Operation
{
            int i1,i2,i3;
            void add()
            {
i1 =10;
i2 = 20;
i3 = i1 + i2;
                        System.out.println(“Sum of the integers”, +i3);
            }
};

class FloatSum extends Operation
{
            float f1,f2,f3;
            void add()
            {
f1 =1.5f;
f2 = 2.5f;
f3 = f1 + f2;
                        System.Out.println(“Sum of the floats”, +f3);
            }
};

Class AbstractDemo
{
            public static void main(String args[ ])
            {
                        Operation o;
                       
o = new Intsum();
                        o.add();
                       
o = new Floatsum();
                        o.add();
            }
};

·         An object of the abstract class but not create directly but it can be created indirectly. It means that no allocation of memory by using new keyword.
·         An object of an abstract class is nothing but an object of that class which is extending this abstract class.
·         Every abstract class if further extendable / reusable.
·         Abstract class could not be final.

Note: - If we have four classes in the 4 different files then we are not using semicolon (;) mark at the end of each class but if we have 4 classes in the same java file then we have to terminate classes one after another.
·         Abstract base class: An abstract base class is one which contains physical representation of abstract methods.
·         Abstract derived class: An abstract derived class is one which contains logical representation of abstract methods which are inherited from abstract base class.
·         We can create an object of an abstract class indirectly in 2 ways: -
1)      We can create the object of that class (Derived) which is extending the abstract class and the object of that derived class will become the object of the abstract class.     
2)      We can use the “factory methods”.

Factory Methods:
·         A factory method is that whose return type is similar to the name of the class where it presented.
·         Factory methods are used to create an object of the class without using the “new” keyword.

Rules for the factory method: -
1)      Return type of the factory method must be similar to the name of the class.
2)      Every factory method must be “static”.
3)      Every factory method must be “public”.        

Sample Example:

import java.awt.GraphicsEnvironment;
class FactoryFonts
{
            public static void main(String args[ ])
            {
GraphicEnvironment ge =  GraphicEnvironment.getLocalGraphicsEnvironment(); //Factory Method
                        String fonts = ge.getAvailableFontFamilyNames();
                        Syatem.out.println (“Total available fonts: ”, +fonts.lenght);
                        Syatem.out.println (“Available fonts names: “);
                        for(int i = 0;i< font.lenght; i++)
                        {
                                    System.out.println (“Font Name: “, +fonts[i]);
                        }
}
}

In the above program ,”awt” is a package, which is used here to import a class “GraphicsEnviorment” now this “GraphicsEnviorment”  is an abstract class and it has an abstarct method getLocalGraphicsEnviorment().

The above program collects and prints all the system fonts.

Inheritance in java and Use of "super" and "super()"



Inheritance:

o   Inheritance is a process of reusing the features (Data members and member methods) of base class into derived class.
o   A base class is one which always gives its features to the derived class.
o   A derived class is one which contains its own features as well as the features from its base class.
o   Syntax for inheriting the features from the base class to derived class:
class <DerivedClassName> extends <BaseClassName>
{
      Variable declaration
      Method definitions
}
o   Here <DerivedClassName> and <BaseClassName> are the names of derived and base classes respectively.
o   Here “extends” is a reserved keyword which is used for inheriting the base class data members and methods into derived class and it also improves the functionality of the derived class.
o   It is strongly recommended to create an object of bottom most derived class since it contains the features of its own as well as its parent class features too.
o   When we create an object of bottom most derived class, JVM always creates the memory space for the data members of the super class first and later it creates the memory space for the data members of the derived class.
o   Once the base class is declared as final, it can’t be inherited into derived class.
o   Private data members of the base class will not be inherited into derived class.
o   For each and every class in Java, there is a super class called Object class. This class supplies gc () i.e. garbage Collector.
o   When the base class is containing final methods then in derived class the final methods will be inherited but we can’t change the definitions i.e. we can reuse but can’t override.

The “super” keyword:

o   “super” is a keyword which is used to differentiate the Base-class features from the derived-class features with in a derived-class if and only if they are similar.
o   The keyword “super” plays important roles at 3 levels. They are:
    • At variable level
    • At method level
    • At constructor level
o             “super” at variable level:
§  Whenever we inherit the data members from the base class to the derived class then there is a possibility  that the base class members are similar to the derived class members.
§  In order to distinguish the base class data members with derived class data members, the base class data members must be preceded with “super” keyword in the context of derived class.
§  Syntax:
super.baseClassDataMember;

o   “super” at method level:
§  Whenever we inherit methods from the base class to the derived class, there is a possibility that the base class methods are similar to the derived class methods.
§  In order to differentiate the base class methods derived class methods, the base class methods must be preceded with “super” keyword in the context of derived class.
§  Syntax:
super.baseClassMethodName();

o   “super” at constructor level:
§  Whenever we develop any application using the concept of inheritance, it contains base class, derived class and intermediate base classes.
§  When we create an object of the bottom most derived class, it calls object creation of its immediate super class automatically. An object of the immediate super class is nothing but an object of its top most super class i.e. an object of the bottom most derived class is nothing but an object of its immediate super class.
§  Hence, the constructors are being called from bottom most derived class to top most base class and they are being executed from top most base class to bottom most derived class.
§  An object of the derived class can be created with respect to either default or parameterized constructor.
§  Take the following diagram to understand the concept of super at constructor level:





o   super() :

o   This constructor is used to call the default constructor of the base class from the default constructor or parameterized constructor of derived class in context of derived class.

o   super(…)

§  This constructor is used to call the parameterized constructor of the base class from the default or parameterized constructor of the derived class in the context of derived class.

Rule 1: Whenever we want to call the default constructor of the base class from the default constructor of the derived class, using super () is optional.

Rule 2: Whenever we want to call the parameterized constructor of the base class from the parameterized constructor of the derived class, using super (…) is mandatory.

Rule 3: Whenever we want to call the default constructor of the base class from the parameterized constructor of the derived class, using super () is optional.

Rule 4: Whenever we want to call the parameterized constructor of the base class from the default constructor of the derived class, using super (…) is mandatory.

Note: whenever we make a call for either super () or super (…), they must be the first statement in the derived class constructors.

Example Program:

class Base
{
                        int a,b;
                        Base()  
                        {
                                     a=2; b=3;
                                    System.out.println("I am in default constructor of Base class.");
                                    System.out.println(" values of a:" +a);
                                    System.out.println(" values of b:" +b);
                        }
                        Base(int x)
                        {
                                    this();
                                    a=b=x;
                                    System.out.println("I am in single parameterized constructor of Base.");
                                    System.out.println(" value of a:" +a);
                                    System.out.println(" value of b:" +b);
}
Base(int x,int y)
{
            this(600);
a=x;
b=y;
System.out.println("I am in double parameterized constructor of Base.");
System.out.println("value of a" +a);
System.out.println(" value of b" +b);
}
}
class Derived extends Base
{
                        int m,n;
Derived()
{
super(400, 500);
m=100;
n=200;
                                    System.out.println("I am in default constructor of Derived class.");
System.out.println(" value of a"+m);
System.out.println(" value of b"+n);
}
           
                        Derived(int x)
{
this();
m=n=x;
                                    System.out.println("I am in single parameterized constructor of Derived class.");
System.out.println(" value of a"+m);
System.out.println(" value of b"+n);
}

Derived(int x, int y)
{
this(300);
m=x;
n=y;
System.out.println("I am in double parameterized constructor of Derived class.");
                                    System.out.println(" value of a"+m);
                                    System.out.println(" value of b"+n);
}
}
class SuperDemo
{
public static void main(String args[])
{
Derived d = new Derived(100,200);
}
}