Thursday, March 24, 2016

Java - Interface,multiple inheritance & use in unrelated classes (Mean,Median,Mode example)

Interface is similar to a class,
But  methods in an interface are all only declared, not implemented.
Interface has only the method signature unlike a class,
which also has method body as shown below.

Class                                                                   Interface

class  Displayable {                                        interface Displayable {
public void  display(){                                      public void  display();
System.out.println(" Display method");}            }                                   
 }                                                

That is, Interfaces can have only Abstract methods.
But, we also have Abstract classes,which can have only abstract methods.
(Abstract classes can have both abstract and functional methods).
Then the question would be,
If we can have an abstract class with abstract methods, why we need Interface feature.
There are two reasons for it,

One:

Abstract class is a CLASS, where as Interface is not a class.
The advantage is,
In Java, a Class can EXTEND only one class but a class can IMPLEMENT
more than one interface.
Added to that, an Interface can EXTEND more than one Interface.

This feature of Interface enable Java to achieve multiple inheritances, 
which is not directly possible with class.

Second:

Abstract class being a class, it is used in classes which are related.
Whereas, Interface, which is not a class, can be implemented by classes
which are not related.

We will see the above advantages with examples.

Example Program with multiple inheritance:

A software company has employees under the categories as Programmers, Testers
and Programmer cum Testers.

Here,
We can have an Employee Class with personal details of employees
And, we can have subclasses for Programmers and Testers separately by
EXTENDING Employee class as below.

class programmers extends employee{
.....}

class testers extends employee{
.....}

But, we can't have a class for employees,who are both Programmers and Testers by Extending class.
Because,we can't  extend more than one class - no subclass can have more than one super class.
That is,

class progCumTesters extends programmers, testers {
}
is wrong.

In these situations, Interface feature comes to our aid.
Because, we can't extend more than one class but we can implement interfaces.
We can have a class like,

class progCumTesters extends programmers implements testerinterface{
}

Here, we create an Interface for Tester details and implement it along
with Programmer class extension.

Program:

package multipleinheritance;

/* Employee base class */
class employee {
void eDetail(int eId,String eName){    
   System.out.println("Employee Id = "+eId);
   System.out.println("Employee Name = "+eName);
}
   
}
/* Programmer subclass with employee detail inherited from Employee class */
 class programmer extends employee {
        void programmerDetail(){
          System.out.println("Programmer Skill Details");
    }
    }
/* Tester subclass with employee detail inherited from Employee class */
class tester extends employee {
    void testerDetail(){
        System.out.println("Tester Skill Details");
}
}
/* Tester Interface to enable multiple inheritance */
interface testerInterface{
    void testerDetail();
    
}

/* Programmer cum Tester class inherits Employee and Programmer detail
   from programmer class and implemets Tester skills through Tester Interface */  
class programmerCumTester extends programmer implements testerInterface{
     public void testerDetail(){
        System.out.println("Tester Skill Details");
    };
}
   
public class MultipleInheritance {

    public static void main(String[] args) {
       
        System.out.println("EMPLOYEE as PROGRAMMER \n");
        programmer p = new programmer(); // programmer object
        p.eDetail (111, "Wilson");
        p.programmerDetail();
        System.out.println("\nEMPLOYEE as TESTER \n");
        tester t = new tester();      // Tester Object
        t.eDetail (111, "Wilson");
        t.testerDetail();
        System.out.println("\nEMPLOYEE as PROGRAMMER cum TESTER\n");
        // programmer cum Tester Object
        programmerCumTester pt = new programmerCumTester(); 
        pt.eDetail(111,"Wilson");
        pt.programmerDetail();
        pt.testerDetail();
    }
    
}

Output:
EMPLOYEE as PROGRAMMER

Employee Id = 111
Employee Name = Wilson
Programmer Skill Details

EMPLOYEE as TESTER

Employee Id = 111
Employee Name = Wilson
Tester Skill Details

EMPLOYEE as PROGRAMMER cum TESTER

Employee Id = 111
Employee Name = Wilson
Programmer Skill Details
Tester Skill Details

Example Program for using interface in unrelated classes.

An educational center wants arithmetic average (mean) of student marks.
A home buyer wants medium(median) cost house, that is middle value  -
neither low and nor high cost wise.
A Foot Wear company want to know which size would sell most (mode) in the market.
That is, which size has the highest frequency in a given set.
Naturally they belong to three different classes. 

The above three situations are very different and they require three different type
of averages to be calculated.
But a common Interface can be implemented in the above different classes.

In this example, an Interface Average is created with method signatures for
Mean,Median and Mode averages.
Interface methods are implemented in the corresponding classes.
Mean method in Education Center.
Median method in Housing Company.
Mode methods in Foot Wear Company.

Program:

package interfaceexampe2;
import java.util.Arrays;

interface AverageInterface{
  int mean();// Arithmetic average
  int median();//Middle value in the list
  int mode(); // Most common number present in the list
}
/*
AverageInterface used in an Education Center situation
An educational center would look for MEAN score of a student
 */
class Average implements AverageInterface{
     public int mean(){
int marks[] = {55,65,75,85,95};
    int i,sum =0;
    for (i=0;i< marks.length;i++){
        sum=sum +marks[i];
    }
    int meanAve = sum/marks.length;
      for (i=0;i< marks.length;i++){
    System.out.print(marks[i]+" ");
      }
      return meanAve;

     }
/*
AverageInterface used in an Housing Company situation
An average home buyer would look for mid (MEDIAN) value home,
which is neither low nor high 
*/
     public int median(){
     int i=0;
     
int housePrices[] = {20000,30000,40000,60000,70000,80000};
for (i=0;i< housePrices.length;i++){
    System.out.print(housePrices[i]+" ");
      }
      int medianAve = housePrices[housePrices.length/2];
      return medianAve;
     }
/*
AverageInterface used in a Foot Wear Company situation
Company would look for most frequently(MODE) bought foot wear
 size for production or marketing
*/
     
    public int mode(){
    int i=0;
    int MostSaleable=0, cnt=0,mostFrequent=0;
    int footwear[]={7,7,8,8,8,9,9,9,9,10,11,11};
    for (i = 0; i < footwear.length; ++i) {
      cnt = 0;
      for (int j = 0; j < footwear.length; ++j) {
       if (footwear[j] == footwear[i]) 
            cnt =cnt +1;
        }
        if (cnt > mostFrequent) {
            mostFrequent = cnt;
            MostSaleable = footwear[i];
        }
    }
    for (i=0;i< footwear.length;i++){
    System.out.print(footwear[i]+" ");
      }
    return MostSaleable;
                   }
                 }
   
public class InterfaceExampe2 {

    public static void main(String[] args) {
   
     Average mmm = new Average();
     System.out.println("Education Center - Student Marks");
     System.out.println("\nMEAN  (Arithmatic average of the Student) : "+ mmm.mean());
     System.out.println("\nHousing Company - Cost of Houses");
     System.out.println("\nMEDIAN(neither low,nor high value of a house) :"+ mmm.median());
     System.out.println("\nShoe Company - Shoe size list");
     System.out.println("\nMODE  (Most Saleable Foot Wear Size) ="+ mmm.mode());
             
    }
    
}

Output:

run:
Education Center - Student Marks
55 65 75 85 95 
MEAN  (Arithmatic average of the Student) : 75

Housing Company - Cost of Houses
20000 30000 40000 60000 70000 80000 
MEDIAN(neither low,nor high value of a house) :60000

Foot Wear Company - Foot Wear size set
7 7 8 8 8 9 9 9 9 10 11 11 
MODE  (Most Saleable Foot Wear Size) =9

Some important points : 

- All methods in an Interface are abstract
- All variables are public,static and final( no need to specify)
- Methods are to be overridden,so they can't be private, protected or final.






Saturday, March 12, 2016

Java - Constructor & Overloaded Constructor with simple example

In Java classes, we have methods that operate on the data.
Constructor is also a method but with a special function.
Its function is to initialize the class attributes automatically when an object of the class is created.
Constructor method is not called in the program like normal methods, it  is invoked automatically when an object of the class is created.
It is called as constructor because it constructs the object with values after creation.

How we distinguish this special method from other methods in a class?

Distinction between constructor method and other methods is in the name of the method.
Constructor method carries the same name as that of the class, not user defined names.

Can the values set by the constructor be changed ?

They can be changed,
Though constructor initialize the attributes of a class with default values,
Those values can be changed by another feature called as OVERLOADED CONSTRUCTOR.
The difference between the default constructor and overloaded constructor is,
The default constructor simply  assigns default values to the attributes of a class after creation of the object automatically.
It  has no parameters and does not return any values.
Whereas,
The overloaded constructor methods have parameters.
Through arguments, they assign user supplied values to the attributes of a class, thus changing the values set by the default constructor.

How many overloaded constructor  a class can have?

A class can have more than one overloaded constructor provided they carry different method signature.
Though default constructor and overloaded constructors have the same name, they should have different method signature.
(Signature of a method constitutes Name, number of arguments and type of arguments.)

As far as access,
Based on access specifics (public, private, protected), features are accessible to other classes.
By default they have friendly access – accessible to whole package.

Example:

We will see a simple example.
A pizza shops sells pizzas of three sizes - Standard,Medium and Large.
Supposing they sell around 90 standard size pizzas out of every hundred.
Then, they would maintain values of a Standard size pizza as default values,
so that they need not type detail whenever  a standard pizza is ordered.
This will save time, since it constitutes 90 percent of sales volume.
But, out of every 100 pizza, they also sell 10 pizzas of medium and large size.
So, they have to overload the default values as well.
The following program illustrates how default and overloaded constructors can be implemented.

Program -


package constructorexp;
import java.util.Scanner;     // for user input

class pizza{
    String item;
    String size;

    /* Default CONSTRUCTOR */

    pizza(){
    item = "Pizza";
    size ="Standard";
    }

    /* Overloaded CONSTRUCTOR */

   pizza(String sze){     // Has a parameter for user value for size of pizza
   item = "Pizza";
   size = sze;                // User value is assigned to the attribute
    }
   
}  

public class ConstructorExp {

    public static void main(String[] args) {
        String Wsize = "";                                              // for user input for size
        Scanner Accept = new Scanner(System.in);     // object for user input
System.out.println("Enter Size of Pizza (L-Large,M-Medium, [Enter] for Standard");  
       Wsize = Accept.nextLine();                             //method for String input
            
              /* Display of overloaded user values for LARGE Pizza */

        if (Wsize.equals("L")){
        pizza op = new pizza("Large");     // object from overloaded constructor
        System.out.println("Overloaded Constructor --");
        System.out.println("Item type:"+ op.item + ", Size:"+op.size);
        
    }

        /* Display of overloaded user values for MEDIUM Pizza */

        else if (Wsize.equals("M")){
        pizza op = new pizza("Medium");     // object from overloaded constructor
        System.out.println("Overloaded Constructor --");
        System.out.println("Item type:"+ op.item + ", Size:"+op.size);
        
        }
       else{

              /* Display of default values by default constructor */ 

      pizza p = new pizza();                        // Object from default constructor
      System.out.println("Default Constructor --");
      System.out.println( "Item type:"+ p.item + ", Size:"+p.size);
           }
     
    }
    
}

Output :
run:
Enter Size of Pizza (L-Large,M-Medium, [Enter] for Standard
<enter>
Default Constructor --
Item type:Pizza, Size:Standard

Enter Size of Pizza (L-Large,M-Medium, [Enter] for Standard
M
Overloaded Constructor --
Item type:Pizza, Size:Medium

Enter Size of Pizza (L-Large,M-Medium, [Enter] for Standard
L
Overloaded Constructor --
Item type:Pizza, Size:Large


Friday, March 4, 2016

Java - Abstract Class with Abstract & Functional Methods with simple example

What is an abstract ?
Let us take the word shape.
The very word shape is abstract, when we say shape, 
we can think of many objects but nothing in particular.
We can't say whether it is a circle or a triangle or some other shape.

The shapes Circle, Triangle and Rectangle are concrete objects.
But Shape is abstract. It has no concrete reality.
The word shape lacks DETAIL to define any particular shape but at the same it DECLARES what it is about.
Abstract class in Java is very similar to that.
An abstract class declares what the class is about but do not contain the implementation details.

As we can't think of an object with the word shape, 
we can't create an object instance with the abstract class in Java. 
But, from shape we can derive Circle, Triangle etc.
Similarly, 
keeping abstract class as superclass we can derive subclasses, implement details and create objects.

Coming to methods,
Abstract class may contain abstract methods (methods declared but not implemented) as well as functional methods (methods fully implemented). 
Those abstract methods must be implemented in the derived classes, otherwise derived classes will be considered as an abstract class only.

We will see two simple examples -one with abstract method and another with functional method. 

Programs:

Example -1 : Abstract class with abstract method.

/* Abstract class 'shape' with abstract 'Area' method */
abstract class Shape{
    abstract float Area();
}
/* Subclasses Circle, Rectangle, Triangle with method 'Area' implemented accordingly */
class Circle extends Shape {
   float radius=10;
    float Area(){
        return( (22/7) * radius*radius);
    }
}
class Rectangle extends Shape {
    float length =10, breath = 5;
        float Area(){
        return(length*breath);
    }
}  

class Triangle extends Shape {
     float base =10, height = 5;
        float Area(){
        return(base*height)/2;
    }
}  

/* main program */
public class AbstractClsExp1 {

    public static void main(String[] args) {
      /* Object Instant creation through subclasses Circle,Rectangle and Triangle */
        Circle CirObj = new Circle();
        Rectangle RecObj = new Rectangle();
        Triangle TriObj = new Triangle();
      /* calculating & displaying area through 'Area' method in respective objects */ 
         System.out.println( "Circle : Radius = " + CirObj.radius + ",Area = " + CirObj.Area());
         System.out.println( "Rectangle : Length = " + RecObj.length + ", Breath = " + RecObj.breath + ", Area = " +RecObj.Area());
         System.out.println( "Triangle : Base = " + TriObj.base + ", Height = " + TriObj.height + ", Area = " + TriObj.Area());
    }
    
}

Output :
run:
Circle : Radius = 10.0,Area = 300.0
Rectangle : Length = 10.0, Breath = 5.0, Area = 50.0
Triangle : Base = 10.0, Height = 5.0, Area = 25.0

Example -2 : Abstract class with functional method.
         
 /* abstract class 'shape' with functional method 'Area'
    It has 3 parameters, 's' for particular shape, 
    p1,p2 for radius,length,breath,base,height accordingly 
*/
abstract class Shape{
     float Area(String s, float p1,float p2){
         float a=0;
         if (s == "r"){ a= p1*p2;}
         if (s == "c"){ a= (22/7)*p1*p1;}
         if (s == "t"){a= ((p1*p2)/2);}
         return a;
     }
}
/* derived class 'CRT' (circle,rectangle,triangle) from 'Shape' */

class CRT extends Shape{
     
}

/* main program */

public class AbstractClssExp {
       public static void main(String[] args) {

        float radius = 10, length =10, breath=5,   base=10,  height=6;
        CRT  CRTObj= new CRT(); // object instant creation
        
        /* same method 'Area' is used to calculate area of three different shapes 
           by passing corresponding parameters 
        */
        float CirArea= CRTObj.Area("c",radius,0);
        float RecArea= CRTObj.Area("r",length,breath);
        float TriArea= CRTObj.Area("t",base,height);
              
       System.out.println("Circle - Radius = "  + radius + " ,Area = "+ CirArea);
       System.out.println("Rectangle - Length = "+length+" ,Breath = "+ breath+
                                        " ,Area = "+ RecArea);
       System.out.println("Triangle - Base = "+base+" ,Height "+ height+
                                        ", Area = " + TriArea);
    }
    
}

Output :
run:
Circle - Radius = 10.0 ,Area = 300.0
Rectangle - Length = 10.0 ,Breath = 5.0 ,Area = 50.0
Triangle - Base = 10.0 ,Height 6.0, Area = 30.0

* All abstract classes  are public by default..
* In the earlier versions ,an abstract class must have at least one abstract method,
but not so now. Now, an abstract class need not have any abstract method.
Still, one may maintain the earlier condition for other programming reasons, 
which is  subjective.




Tuesday, March 1, 2016

Java - Difference between Method Overloading and Overridding



1.  Overloading is different methods with the same name              
     Overriding is same method with different implementation.                    

2. Overloading methods are present in the same class.
    Overriding methods are present in different classes (Inherited classes).

3. Names of Overloading methods are same but other parameters are different.
    All parameters of Overriding and Overridden methods are same.

4. Overloading methods are resolved during compile time
    Overriding methods are resolved during run time.

5. Return type of the method is not part of method's signature.
    So same/different return type do not make any difference.
    Return type of Overriding and Overridden methods must be same.

Overloading Example

Overriding Example