Reveal the Programing to an Interface Design principles in java.



Programming to an Interface    

I think it will better to discuss design principals in java based on which design patterns are created.

The very first principal is “Programming to an Interface” what does it mean?

Let try to understand the principal in details.

In general, scenario, if you look at any problem statement or business solution you can find two parts.

1.    Fixed part.
2.    Variable

The fixed part is some kind boilerplate code. But when we design we take care of the variable part.
All the design patterns are discovered to maintain this variable parts. Because they are ever-changing. If your code is not flexible with future enhancement, then your code is not up to the mark.

The question is in java How you can maintain your variable parts?
To drill down to answer let magnify the statement "maintain variable parts". we know same will perform an operation but we don’t know How we can achieve this  operation . Specifically, we know the type of the operation but don’t know details of the implementation moreover client needs can be changed so operation implementation  change in future.

Let’s, take an Example A computer monitor is design for display purpose. So I can say if Computer is a product and Computer monitor is a part of computer product.,then Computer monitor is responsible for display operation.

Now, later on, client needs is changed ,now they want to display by Projector

So If our solution is not capable of welcome this needs it will be nothing but a waste product.

According to new needs what we can analyse is, it will perform same action display but the module should change from Computer monitor to Projector.

So display module in Computer product should be flexible so we can change it easily. Or we can change it dynamically(runtime). We can say display module is like a strategy  and client change the strategy now.

So our java solution is like following.

interface displayModule
{
 public void display();
}

public class Monitor implements displayModule
{
public void display()
{
s.o.p(“Display through Monitor”);
}



public class Projector implements displayModule
{
public void display()
{
s.o.p(“Display through projector”);
}


public class Computer
{
 displayModule dm;

public void setDisplayModule(displayModule dm)
{
this.dm=dm;
}

public void display()
{
 dm.display();
}


public static void main(String args[])
{
Computer cm =new Computer();
displayModule dm = new Monitor();
displayModule dm1 = new Projector();
cm. setDisplayModule(dm);
cm. display();
cm. setDisplayModule(dm1);
cm. display();


}                                                                                                    


}

Look the solution, we know Display Module should be flexible, and we know the operation of the display module is "display" but according to the client it may be changed later, but in a computer, there should always be a display module but we don’t know what will that equipment. It’s may be monitor or projector or any other.


So we create an interface and every Display parts should implement that and provide the own definition of the display.

Look the computer class here I create HAS-A relation call display-module because we know display module change frequently as per client needs so we always make display module as abstract
So we can change it runtime with actual implementation.

Remember always code through an interface so you can change your strategy run-time with actual implementation.
The interface means here java interface or abstract class.
Make the variable parts as an interface or abstract class as you know the operation which is never changes but it implementation or the implement module can change.

Refactoring legacy code to support Multithreading Enviroment




Refactoring Java code for Multithreading Environment


In my service life frequently I encounter a problem that a code is giving weird result in staging or production but when it runs from developer machine it shows a perfect result.

So, the clue is the weird result, try to run it many times and watch result pattern if it is varying then definitely it is due to threading. You can take Thread Dump for analysis but multiple tests give you a rough idea about Thread Problem.

Staging or production are  distributed environment where your resources are shared among multiple requests whereas developing machine there is only one thread involved. So it is run fine in developer machine.


It is very important to design your code for Multithreaded environment.

In this context, I can recall that once I have faced a problem , a module was designed for the stand-alone application. so developer implements the code without thinking of Multithreading as they know they will package the code into a jar then invoke from a command line which spawns a JVM and serves only one request.
So far so good but later a new change request comes that it should be hosted in Web, not as a standalone app. The Web means multiple requests so A New Problem was raised from nowhere. So there is no way but has to refactor the module to support Multithreading.

There are so many classes in a module some of them are pivot classes. Make it multithreaded capable is not an easy task. So we have to think a procedure by which we can do it in less time and minimally affecting the classes.

I want to share that experience with you people.

In that course, we think and try to understand where and How Multithread environment differs from a single thread environment.

Outcomes are.
1.       In Multithread environment problem occurs for the shareable resource which is not synchronized.
2.       If I filter the statement 1 , more specifically I can say shareable resource can create a problem If at least  one thread wants to update/write it states . then only we can encounter dirty data.
3.       If Multiple threads want to read from a resource, then we don’t need to alter them as It will not harm the state.
4.       What makes a shareable resource?
5.       If in a class, member variables are defined and have setter method then these classes are the potential candidate for causing the problem.
6.      If a class has methods and all variables are method level, then they inherently thread safe. We don’t bother them.
7.       If a class has Static variables they are very dangerous as the static variable bound to class and one copy shared by all Objects so, If a thread changes its value it reflects for all objects.
8.       In a project, I see every utility classes design as Singleton so we have to mark them candidate of Multithreading refactoring.
9.      In a project, it often happens a step is dependent on a previous stem or some derived value generated by some business logic. The developer is maintaining them as in Cache or in a Context and they are the potential candidate for Multithreading.
10.   Try to find any immutable class then they are thread safe so don’t need to refactor them.


Based on the Outcome we target our module and Identifies the classes need to be refactored. Believe me
This exercise will help you to find exact classes you need to refactor and you can discover they are the High-level classes like the manager or any factory classes Utility classes etc.

Next, the important question How to refactor them?

To Refactor they put your thinking Cap and try to pick the tools which will cause minimal change.

Tool 1:
Check you can refactor all member variable to method variable.
First check in that class how many methods use this member variable, then try to find out by searching your workspace from where these methods are called. If the number are small pass that variable as the method parameter and remove the member variable.

Suppose in EmployeeManager class Employee is member variable and in checkValidEmploye is method where you use Employee Object

Code snippet

Public class EmployeeManager
{
Employee emp;
Public void checkValidEmploye()
{
//some code using emp variable
}
}

Refactor the code

Code

Public class EmployeeManager
{
//Employee emp;// remove it
Public void checkValidEmploye(Employee  emp)
{
//some code using method emp variable
}
}

Call  employeeManager. checkValidEmploye(new Employee  ());



Tool2:

If there are so many member variables and you can’t make it local variables

Put the class in ThreadLocal

Code snippet
EmployeeManager mgr;
Public void validate()
{
                mgr. . checkValidEmploye();
               
}


Refactor Code snippet
private static ThreadLocal< EmployeeManager > THREAD_LOCAL_CACHE = new ThreadLocal< EmployeeManager >();;
Public void validate()
{

If(THREAD_LOCAL_CACHE.get() !=null)
{
       THREAD_LOCAL_CACHE.get(). . checkValidEmploye();
}
Else
{
THREAD_LOCAL_CACHE.set(new EmployeeManager() )
THREAD_LOCAL_CACHE.get(). . checkValidEmploye();
}             
               
}


By Thread Local we can ensure An EmployeeManager object exist for a thread. So EmployeeManager would be thread specific so no other thread can access one thread’s Employee manager. So mitigate the risk of dirty data


Tool3> Identify the classes which are singleton basically context,cache,utility classes are a singleton so make it thread safe. We can make it to Per thread Per singleton

Refactor singleton to normal class by a trick we can do that


Single to class look like

public class Utility
{
 private  static  Utility instance= new Utility();
private Utility()
{
}
Public static Utility  getInstance(){
return instance;
}


Refactor it like following to avoid change in calling classes


public class Utility
{

private static ThreadLocal< Utility > THREAD_LOCAL_CACHE = new ThreadLocal< Utility >();;

private Utility()
{
}
Public static Utility  getInstance(){
If(THREAD_LOCAL_CACHE.get()==null)
{
THREAD_LOCAL_CACHE.set(new Utility());
}
return THREAD_LOCAL_CACHE.get();
}

This will solve the multithreading problem as each request it will give a new Utility Object if it does not have as There is one object per thread we can put some variable to it and use it in future .


Please choose the option carefully. This is your experience and design decision which tool you are going to use to alter your code minimally.



















Free Java seminar at Bagbazar on 30-Jul-2016

Free Seminar on Java,  Absolutely free No registration fees . Based on First come
first serve basis
HOST: Shamik Mitra(IBM Tech-Lead)
Agenda
What is java
Why Java programing
OOPS principals
Class and Object
Basic syntax and keywords
Operators
Conditional statemants
Overloading and Overriding basiss
Collection frame works
Data structure
Thread Overview
Discussion



Prerequisite :  Basic knowledge on Computer
Basic sense on programing.

Bring Laptop will be benifical for student.
 
Feel free to contact 10.00 AM to 11 PM.
mob : 9830471739
email : mitrashamik@gmail.com

Pass user input from command line in java

There is a various way, you can pass parameter from a console . Using BufferdReader,InputStream but the easiest way to do it with Scanner class it took Inputstream(System.in) as parameter from we can get user given value

Let see an example



package com.example.userInput;

import java.util.Scanner;

public class UserInput {

    public void add(int i,int j)
    {
        int result = i+j;
        System.out.println("sum is " + result);
    }

    public void multiply(int i,int j)
    {
        int result = i*j;
        System.out.println("
Multiplication  is " + result);
   
    }

    public static void main(String[] args) {
   
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter Choice either a or m");
        System.out.println("Enter First Operend");
        int op1 = sc.nextInt();
        System.out.println("Enter Second Operend");
        int op2 = sc.nextInt();
        System.out.println("Enter Choice");
        String choice = sc.next();
   
   
        UserInput input = new UserInput();
        if("a".equalsIgnoreCase(choice))
        {
            input.add(op1, op2);
        }
        else if("m".equalsIgnoreCase(choice))
        {
            input.multiply(op1, op2);
       
        }
        else
        {
            System.out.println("Wrong choice Entered");
        }


Spring framework download and integration with eclipse step by step.

In this tutorial we will learn how we can download spring framework jars for eclipse and integrate the downloaded spring framework with eclipse . Then we create a basic Spring example to check our setup is successful or not.

Here are the steps to configure Spring core with eclipse IDE

1. Install JDK and eclipse
2. create a java project in eclipse called SpringTest
3. create a folder  lib under SpringTest\lib
4. Download commonLoggin1.2.jar from here http://commons.apache.org/proper/commons-logging/download_logging.cgi

5. extract it and put jars into lib folder earlier created.
6. Download spring from here
http://repo.spring.io/release/org/springframework/spring/4.1.6.RELEASE/
7. extract it and put all jars into the lib folder .
8. Right click on SpringTest ->properties->java build path
9. click on add external   jar and add all jars under lib folder
10.  Create a  folder called configFiles under SpringTest/ src folder.
11. create beans.xml file in configFiles

Add following lines

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.example.HelloWorld">
       <property name="greet" value="Hello World! Welcome to Spring"/>
   </bean>

</beans>


12 Create a package com.example under
SpringTest\src

13. create a java file HelloWorld.java under the package
com.example

14. Write following in HelloWorld


package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorld {
   
    private String greet;

    public String getGreet() {
        return greet;
    }

    public void setGreet(String greet) {
        this.greet = greet;
    }
   
   
    public static void main(String[] args) {
       
        ApplicationContext ctx = new ClassPathXmlApplicationContext("configFiles/beans.xml");
       
        HelloWorld bean =(HelloWorld) ctx.getBean("helloWorld");
        System.out.println(bean.getGreet());
       
       
    }
   
   

}
15. Run as java application output will be
Hello World! Welcome to Spring

multiple inheritance in java?

Java directly does  not support multiple inheritance , but by interface it supports the same.

To understand why java does not support multiple inheritance  first we need to understand the Diamond problem

Diamond problem says

Suppose we have Parent class Color it has a method cal displayColor().

Now it has two children  Yellow and Blue by invoking displayColor(). they return yellow and blue respectively.

Let assume java supports multiple inheritance
So if I create a child say Green which inherits Yellow as well as Blue then which displayColor() color it inherits? It creates an ambiguous  situation so for this reason java does not support multiple inheritance directly but we can solve this problem by the interface. An interface is a contract only methods are declared in  interface no definition so if Green implements yellow and blue ,
Green class easily override displayColor() , and define the same, there will be no problem as only concrete implementation only in Green class.

Example:
public class Color
{
public void displayColor()
{
System.out.println("white");
}
}


public class Yellow extends Color
{
public void displayColor()
{
System.out.println("yellow");
}

}


public class Blue extends Color
{
public void displayColor()
{
System.out.println("blue");
}
}




interface color
{
  void displayColor();
}

interface yellow extends color
{
  void displayColor();
}

interface blue extends color
{
  void displayColor();
}


Class Green implements blue,yellow
{
  public void displayColor()
{
System.out.println("Green")
}

}







Does Java support multiple inheritance?

Java directly does  not support multiple inheritance , but by interface it supports the same.

To understand why java does not support multiple inheritance  first we need to understand the Diamond problem

Diamond problem says

Suppose we have Parent class Color it has a method cal displayColor().

Now it has two children  Yellow and Blue by invoking displayColor(). they return yellow and blue respectively.

Let assume java supports multiple inheritance
So if I create a child say Green which inherits Yellow as well as Blue then which displayColor() color it inherits? It creates an ambiguous  situation so for this reason java does not support multiple inheritance directly but we can solve this problem by the interface. An interface is a contract only methods are declared in  interface no definition so if Green implements yellow and blue ,
Green class easily override displayColor() , and define the same, there will be no problem as only concrete implementation only in Green class.

Example:
public class Color
{
public void displayColor()
{
System.out.println("white");
}
}


public class Yellow extends Color
{
public void displayColor()
{
System.out.println("yellow");
}

}


public class Blue extends Color
{
public void displayColor()
{
System.out.println("blue");
}
}




interface color
{
  void displayColor();
}

interface yellow extends color
{
  void displayColor();
}

interface blue extends color
{
  void displayColor();
}


Class Green implements blue,yellow
{
  public void displayColor()
{
System.out.println("Green")
}

}







Does runtime polymorphism can be acheived by data memebrs?

No Overriding can not be performed on properties/data members it always call the reference class properties value

Let take an example

Public class Father
{

  public  int age=60;

}

Public class Child extends Father
{

  public  int age=30;

}


Now if Father f = new Child();
f.age print 60;

How does Map work in Java?

HashMap in Java works on hashing principle. The Map is a data structure which allows us to store object with a key and retrieve same by the same key. Hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method.

 When we call put method,internally  hashcode() method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal LinkedList. If we dig down the structure we found HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object. When you want to retrieve the object, you call the get() method with  a key object. get() method again generate  key object hash code and eventually ended up with same  bucket location. and returns the value.

Few important things to remember , If you want to use your custom object as a Key of Map

1. It has to be immutable .unless  some one can  change the state.of the object
2. Must override hashcode. As good hashing algorithm, distribution of objects in bucket will be as good
.3. Must override equals method so in  the time of get operation  map  can fetch the key which is identically equal.

public final class CustomKey{
private final String name = "Shamik";
public final String setName(String name)
{
this.name=name;
}
public final String getName(String name){
return name;
}
public int hascode()
{
return name.hascode()*1245/7;
}
public boolean equals(Object obj)
{
if(obj instanceof CustomKey)
{
return this.name.equals(obj.name);
}
return false;
}
}

Here  name is not final so following scenario can occur
CustomKey refKey= new CustomKey();
Map<CustomKey ,String> map = new HashMap<CustomKey,String>();
map.put(refKey,"Shamik");
refKey.setName("Bubun");
map.get(refKey);

It will return null as when equals method invokes it return false. So immutability is must required.

what is servlet collaboration?

Servlet Collaboration means how one servlet can communicate with other. Sometimes servlets are to pass the common information that is to be shared directly by one servlet to another through various invocations of the methods. To perform these operations, each servlet needs to know the other servlet with which it collaborates. Here are several ways to communicate with one another:


1. ServletContext :  In an application, there must be one Servlet context which is shared by all the servlets in this application. It works as a global map .each servlet put  necessary information , which needs to be shared
and other can get that info
  <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.example.ServletTest</servlet-class>
 </servlet>

 <context-param>
   <param-name>name</param-name>
   <param-value>Shamik Mitra</param-value>
 </context-param>




To get this
getServletContext().getInitParameter("email");

Request Dispatcher:
request.setAttribute("name", "Shamik Mitra")
request.getRequestDispatcher("destination_name").forward(req,res);
request.getRequestDispatcher("destination_name").include(req,res);

Java Singleton class :

public class Javacontext
{
   private static Javacontext ctx = new Javacontext();
private String name ="Shamik";
private Javacontext()
{
}
public static Javacontext getInstance()
{
return ctx;
}
public String getname()
{
return name;
}
}


Java Properties: Using java properties you can share information

import java.util.*;

public class PropDemo {

   public static void main(String args[]) {
      Properties prop= new Properties();
     Set<String> key;
   
      prop.put("name", "Shamik Mitra");
   

      // Show all states and capitals in hashtable.
      key= prop.keySet(); // get set-view of keys
      Iterator itr = key.iterator();
      while(itr.hasNext()) {
         str = (String) itr.next();
         System.out.println("The key is" +
            str + " name is " + prop.getProperty(str) + ".");
      }
   
   }
}

Can we Overload Main method in java.

Yes you can overload main method but public static void main(String[] args) is entry point in java. JVM always search for this method.
If it is not present in overloaded version ,when you try to run your code that gives run time exception no main method found.


From public static void main(String[] args), you can call other overloaded main function.

Keep in one thing in mind

If some one write

public static void main(String... args)//Varags

That is equivalent public static void main(String[] args) that will gives you compile time error.

Example :
package com.example.main;

public class OverLoadmain {
   
    public static void main(String[] args) {
       
        System.out.println("I am in main ");
       
    }
   
public static void main(int args) {
   
    System.out.println("I am in int");
       
    }


public static void main(String args) {
    System.out.println("I am in String");
}


/*public static void main(String... args) {
    System.out.println("I amn in varags ");
}*/

}

Display trangle in screen using Java.

package com.example.loop.star;

/*
 *
 * This class display triangle as follows
 *
 *         *
 *        * *
 *      * * * *
 *    * * * * * *     
 */

public class DisplayTrangle {
   
    public void triagle_center(int max){//max means maximum star having
        int n=max/2;
       
        /*This loop prints Top star  as  max star is 20 so i first row we have 19 single blanks and one star to complete left hand
         * So n = 20/2 = 10
         *
         * For first row middle point is 11 th position so 19 single blanks one *
         *
         *
         * Row onwards
         *
         * star = row number * 2 if 1st row 2 stars
         * double blank = middle pos - row number;= 10-1=9 double blanks
         *
         * as middle pos is  11.        *
         *
         *
         * *\
         *
         */
       
        for(int m=0;m<((2*n)-1);m++){//for upper star
            System.out.print(" ");
        }
        System.out.println("*");

        for(int j=1;j<=n;j++){
            for(int i=1;i<=n-j; i++){
                System.out.print("  ");
            }
            for(int k=1;k<=2*j;k++){
            System.out.print("* ");
            }

            System.out.println();
        }


    }
   
   
    public static void main(String[] args) {
       
        DisplayTrangle ref = new DisplayTrangle();
        ref.triagle_center(20);
       
    }


}

Is Spring Bean Thread Safe?

Thread safety is a different context . Singleton spring beans has no relation with thread safety. spring container only manages life-cycle of objects and guaranteed that only one object in spring container. so If an Non thread safe object is injected then obviously it is not thread safe. To make it thread safe you have to handle it by coding.

If it is a web-application , Scope("request") can achieve thread-safety  as for each new request it creates a new object or scope("prototype") will do this.(for each  invocation it creates new bean .)

How do you handle error condition while writing stored procedure or accessing stored procedure from java?

When you call a store procedure the store procedure will execute in database server so if there any exception occurs that can be handled in EXCEPTION block in the store proc. If the store procedure it self fails it throws sql exception which can be handled by try/catch block and wrap it to your project specific exception.


example


try {

CallableStatement stmt=con.prepareCall("{call geNamebyId(?)}");

stmt.setInt(1,123);

stmt.execute();

} catch(SQLException e) {

e.printStack();

throw new CustomException(e);//application specific exception

}

What is JCS?

JCS stands for Java Caching System. This is an open source project and released by Apache written in Java.  Like all other caching system JCS  has following features.

1. JCS supports In memory cache.
2. Provide method for add objects in Cache.
3. provide method for retrieve objects from cache
4. provide method for delete objects from cache


apart from this you also can specify how long a object can store in memory.

JCS is used when a object is very costly, say a Composite object which is created by lots of database call and application use it very often. So it is better to put this object in JCS rather than create a new object instance  every time.

So JCS can be used in every application  which has large number of objects which are very costly and use very often.

JCS provide some additional features like
1. Very good memory management
2.Region data separation and configuration
3. Remote synchronization etc.

How to get client machine name and Ip address from Httpservlet?

In HttpServletRequest there are two methods
 a. getRemoteAddr()
 b. getRemoteHost()
 which will provide the necessary information.
 Actually in request header following information is stored.


Ip address of client m/c = request.getRemoteAddr();

Hostname of client =  request.getRemoteHost()

What is difference between include action and include directive in JSP?



Before starting the difference  discussion,  first, we have to understand the JSP life cycle. when a request first comes to a JSP it will translate into servlet then compile and load into web container for further use. Subsequent requests  will serve by this translated servlet.


Let say we have a JSP page called greet.jsp which includes another JSP call  header.jsp. Now it can be included in two ways
 1. by page directive 
 2. by JSP action tag
1. By page directive : syntax is <%@ include file="header.jsp" %>
now when greet.jsp page translated  into a  servlet all the code written in the header.jsp goes to translated servlet's service()(incase of Httpservlet it's //doget() or dopost()) method. so it acts as one servlet which contains two JSP's code ( header.jsp + greet.jsp  ) and ready for serve subsequent requests. Now in mean time suppose  developer change the content of header.jsp, this change will not reflect to translated servlet as it is already compiled and loaded in the web container  . To make this happen you have to restart web container then it will recompile  but some web container smart enough to pick up this changes. so  include page directive is  not a good option for dynamic pages.


2. By JSP action tag: syntax

<jsp:include page="header.jsp">
 Here inclusion is done at request time so it maintains two servlets unlike page directive so it will show updated value each time.  so action tag is the good choice  for dynamic pages.

Benifits of Static methods

Static keywords mean,  methods/variables attached to class, not with objects. So this variables/methods is shared with all objects instances of this class.Following advantages, we can get using static.

1. We can invoke a static method without creating objects. So Utility methods can be static

example

public class DateUtils
{
    public static Date getSystemdate()
{

    return  new Date(System.currenMillsInSecond());
}

  public static Date getPrevousDay()
{
}

//etc


}

.2. If you want to declare a Global value which will share among objects. suppose wants to calculate hit count of a servlet

public class Countservlet extends HttpServlet
{

    private static  int count = 0;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{

     count++;
}

public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{

   doGet(request,response);
}



}




3. If you want to make a class level synchronization by synchronizing static you can achieve it.


public class Account
{

private static int min_balance=100;

public synchronize void credit(int amount)
{
  min_balance= amount;
}
}


Now no object can change the state of min_balance  as it is class level synchronization.

Can we have main method tn abstract class?

Yes, you can use the main method in abstract class. The main method is a static method so it is associated with Class, not with object/ instance. The abstract is applicable to the object so there is no problem if it contains the main method. In main method, you can not create an instance of the abstract class but you can instantiate other concrete class.


Here is a sample program


public abstract class TestAbstract {

public static void main(String[] args){

System.out.println("Hello world");

}

}



Can we Instantiate Abstract Class?

The main reason is   abstract class may have abstract methods . An abstract method is like template/contract, according to inheritance rule  every concrete subclass must have to provide a concrete definition of the same. So we can say the abstract method is the only declaration.

 Now for a moment we  assume we can create an instance of abstract class


so,  we have an abstract class name Shape and an abstract method getShape()

Abstract class looks like,
public abstract Shape

{

  public abstract getshape(); //Only declaration

}


Now, next step is to create an Object of abstract shape as we assume we can instantiate the abstract class.

 Shape s =new shape();

and call

 s.getshape();


Think what it will return as it is the only declaration!!!! so JVM functionality will break.


Due to that, we can't instantiate the abstract class.

Can we make constuctor as final

No Constructor can never be Final. Only private,public and protected modifiers can use with the constructor.


We use final in method level because  we don't want subclass inherits that method and overwrite it . But constructor is not a method and it can not be overridden as per java specification .

Let's think in a  different way


For say, constructor supports final now that mean's it can't be inherited but if you think about constructor call hierarchy then you can find the first statement of a constructor is super or this, so if the constructor is  not visible how it  can you call the super class constructor ? so we can't call the super class constructor, call hierarchy is uncompleted  so the object will not be created. For this reason, we can't use final in the constructor.

Why we called Java as Platform Independent?

Before starting why we called Java as platform independent I want to share a simple incident with you and understand the Java compilation process in terms of that story.


Say Narendra Modi our respected PM giving a speech in Hindi, Next day in every news daily irrespective of language(Hindi, English, Bengali) this speech is published. Now the question is Narendra Modi give that speech in Hindi so how it translates to English or Bengali seamlessly.


No surprise right, there are reporters for every newspaper they analysis that speech and transform it to another language like English or Bengali.


So I can say theoretically Modi's speech is Language independent as next day everyone sees it in their respective languages.


Java, Does it the same way, It takes your code as input like Modi's live speech and there is Java interpreter which is platform dependent, for Linux, Java provides Linux interpreter for Windows a Windows interpreter, Whose task it taking that input and transform it to Machine code the language OS understand. SO it is like the reporters who translate Modi's speech to respective language.

Now coming to Technical part. 


Actually, to be specific Java compilation is a two-step process Compile then Run Compiler makes the byte code and JVM inter-prate this to machine specific language Here is the trick  I am taking about , Might you have seen when you download JDK there is OS specific version  one is for Unix one is for windows version why so, because  of JVM implementation JVM takes bytecode as input and provide m/c language as output so Linux specific JVM makes Linux specific machine code, windows do the same but as both take bytecode as input you can easily export Windows compile class  Linux m/c That's why they called Java as a platform independent .

Overriding in Java in context of design.


Overriding in Java in context of design.

 


 While you are going for an Interview for a Lead or Developer role. The interviewer will definitely ask you some questions on Overriding and try to puzzle you.


In this tutorial, I try to cover all topics of Overriding so you feel comfortable and easily answer  whatever questions they ask


Definition of Overriding:
In Java, Overriding is a technique by which parent class delegates responsibility to Child. A child can define child specific behavior which will be executed at run time.

From the above definition, it is clear that to do Overriding Parent class and child class is must need, without Child class, we can't achieve overriding, unlike overloading.

Please remember , The interviewer may ask you-- can it be possible to do overriding without child class?

As I said child specific behavior executed at run-time what I mean by this is the  JVM will decide which  Subclass/Object's method it has to call,  so we call it late binding or Dynamic method dispatch.Because runtime JVM decides what to do not at compile time.

Question: What is late binding/ Dynamic method dispatch in Java

If you don't get my point don't worry follow example will clear the concept.



Before dig down to Overriding details let clear one small thing.


The big power of OOP programming is it supports Polymorphic assignment where a parent class reference can point a Subclass object. It will be heavily used in Design pattern or I can say the Whole Design pattern is based on this small concept.

 

Q: What do you mean by polymorphic assignment and Why it is important?


Let's understand why this is important.


say  Foo is Parent class and Bar is child class so we can do that,


Foo foo = new Bar();//Polymorphic assignment.

By parent reference, we can point child Object. It is logical as child inherited all properties of the parent so whatever in parent must have in the child unless properties are private in a parent.


What is the benefits of polymorphic assignment?
 let see the small code

Class Power
{

private Foo f;

public setFoo(Foo f)
{
this.f = f;

}

public void show()
{
f.print();
}
}

Class Foo has a print() method which is overridden in Bar and Zoo two subclasses of Foo

overridden  in Bar
public void print()
{
Sysout(“Bar”);
}


overridden in Zoo
public void print()
{
sysout(“Zoo”);
}

overriding java


so by the setFoo method in Power class, I can easily set Bar or Zoo instance at run time based on some business logic .so when it calls show method based on the subclass it prints Bar or Z

So I can easily change the behavior of the Power class on the fly based on strategy. It is the crux of Strategy design pattern.

But remember, As SetFoo method takes parent reference what ever method are in parent class  you can call those, all Association condition applied here. So if any new method added in subclass that is not visible by parent reference.

Qustion : expect a coding snippet here where interviewr add a method in child and try to call it by polymorphic refrence.

To make it visible you need to do down-casting.

Tip: Always use @Override annotation if you are using Java 5 or more to make sure if maintains all rules of overriding.


To do a perfect overriding we have to follow some rules.

The method which will be overridden must have same data signature also return type will be same

but onwards java 1.5 return type can be subclasses of parent type we say it Co-variant return.
 Q: What is covarient return?


Please follow the following contracts and burn it into the head as in Interview or in Exam you can found various types of combination and you have to find the perfect overridden method.
1. The argument list must exactly match that of the overridden method. If they
don't match, you can end up with an overloaded method .


2. The return type must be the same as, or a subtype of, the return type declared
in the original overridden method in the superclass. we say it covariant return


3. The access level can't be more restrictive than the overridden methods.
The access level CAN be less restrictive than that of the overridden method.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override
any superclass method that is not marked private or final. A subclass in a
different package can override only those non-final methods marked public
or protected (since protected methods are inherited by the subclass).

4. The overriding method CAN throw any unchecked (runtime) exception,
regardless of whether the overridden method declares the exception.

5. The overriding method must NOT throw checked exceptions that are new
or broader than those declared by the overridden method. For example, a
the method that declares a FileNotFoundException cannot be overridden by a
the method that declares an SQLException, Exception, or any other non-runtime
exception unless it's a subclass of FileNotFoundException.

6. The overriding method can throw narrower or fewer exceptions.

Overloading in java

In Interview, you can expect a bunch of questions over overloading and believe me those are very tricky, If you are not understand overloading then it will be very tough to crack interview as this is the fundamentals of Java.

NB: Many people think overloading is very easy but go through the article you will find it is not so easy when overloading comes with boxing,varags, and Widening. 


In this article, we are going to discuss Overloading and it's complexity.

By definition, if two or more methods in a class or in a parent class and child class have the same name but different data signature irrespective of return type called Overloading.


so following example is a  valid overloading is

public class OverLoadtest {


    public void test(int i)
    {
        System.out.println("overloaded 1");
    }

    public void test(long j)
    {
        System.out.println("overloaded 2");
    }

    public static void main(String[] args) {
   
        OverLoadtest test = new OverLoadtest();
   
    }

}

Overloading has some contracts when you are doing a over loading please remember this contracts.

a.  Overloaded methods MUST change the argument list.
b.  Overloaded methods CAN change the return type.
c. Overloaded methods CAN change the access modifier.
d  Overloaded methods CAN declare new or broader checked exceptions.

so

public void do(int i) throws AirithmeticException;
public void do(long j)
public int do(double j)
private int do(String j)
private void do()
throws Exception;

all are valid overloading

overloading in java
Add caption




Now we are talking about some puzzle over overloading

a. doX(int i,long j)
   doX(long j,int i,)
is this  a valid overloading???

The answer is Yes Data signature is different although method meaning is same as only arguments are swap their space.

b. doX(int i)
doX(Integer i) and we call by doX(2);

can you guess which method should be called?

Think......

It will call do(int i)
 as in overloading precedence always over in primitive type;

c. doX(Integer i);
doX(int ... i); now calling doX(2);

 can you tell which version will be called?

It calls do(Integer i); as in overloading, Boxing has precedence over varargs.

d. doX(Integer i) and doX(long i) calling with doX(2)

now here it will call do(long i) as in overloading primitive widening has precedence over boxing .

e. do(Object i)
do(Long i)
 call with do(2) can you tell which version will be called

it calls do(Object i)  version
In Overloading Boxing then widening is permissible, mean here conversion is
int->Integer->Object (boxing then Widening)
 but do(Long i) int->long->Long widening then boxing will not allow.

so remember the following rules to determine which version will be called.

1. Primitive widening uses the "smallest" method argument possible.
2. Used individually, boxing and var-args are compatible with overloading.
3. You can't widen from one wrapper type to another. (IS-A fails.)
4. You can't widen and then box. (An int can't become a Long.)
5. You can box and then widen. (An int can become an Object, via Integer.)
6. You can combine var-args with either widening or boxing.

see Overriding related interview questions also.





Understanding Casting in Java

Understanding Casting in Java

In Java, Casting means to cast a class to another class. This definition has two catch points.


a. Can I cast any Java /custom type(class) to another Java/custom type: No You can only cast those classes to one another which are in the same inheritance tree. You can go back and forth but you are not allowed to cast one class to another type class. So you are able to cast child to parent or parent to child, but not able to cast between another type of class even siblings !!!!

Example :

Class A : Base class
Class B : subclass of A
Class C : subclass of A
Class D : Subclass of B

Then we can cast B to A and D but not C.

b. How many  types of Casting are there in Java:

There are two types of casting
a. Upcasting
b. DownCasting

Upcasting : When a Subclass is cast to parent that is called Upcasting. In Java, every polymorphic assignment is that type of casting. To do that you do not have to bother about explicit casting. this is logical because inheritance means inheriting   the properties of a parent into the child so you can easily say, property exists in the child also exists in the parent.

Subclass = parent properties  + it's own property

so ,

A a=null;
B b =new B(); //B extends A
a =b;//Up-casted no need to explicit casting.


DownCasting:
When a parent cast to its child it called downcasting and explicitly casting is needed here. It is logical as Parent does not know which child it needs to be cast more over parent does not know about Child's own properties.
so
Parent = subclass - Subclass own property


B b =null;   //B extends A
A a = new B();//polymorphic assignment.
b =(B)a; // need  explicit casting as ref a does not know about Object B.




Now add some complexity

Try to guess What will happen?

B b =null;   //B extends A
A a = new A();
b =(B)a; // need  explicit casting.

as although here, Compiler will not complain, but b reference holds an object of A, so when you called class B's own property through reference b. Actual  A object does not have that property and throws a run-time exception. So be careful about Downcasting.

Diagram


















Understand protected modifier in java

Understanding most critical access modifier  protected in java?


We all know Java has three access modifiers a, public b. protected c. private and four access levels  a.public b. protected c. private d. default among them protected is the most critical modifier to understand.


Definition of protected
protected is same as default modifier, which can be accessed by other classes in the same package but the only difference is it can also be accessed by sub classes from outside packages through inheritance.

Now there are two catch points

1. What do you mean by accessed?
2. What do you mean by access through inheritance?

1. What do you mean by accessed?


In Java, we can access properties of other classes by two ways

a. Association (HAS A)
b. Inheritance (IS-A)

Scenario a.

package com.bar;
public class Bar
{
 protected String greet = "Hello";
}



package com.foo;
public class Foo extends Bar
{
Bar bar = new Bar(); // Bar HAS A relationship with Foo(Association)

bar.greet; //not compiled as no visibility through association

}



Scenario b

package com.bar
Class Bar
{
 protected String greet = "Hello";
}


package com.foo
Class Foo extends Bar
{


System.out.println(greet); //accessd through Inheritence so it prints Hello

}



Association means a class has a reference to another class  as you see in Scenario a.

Inheritance means  a class inheriting parent class property.
The Answer is  no as by rule protected is visible only through inheritance so although class Foo extends Bar but we are trying to access greet variable through association which is not acceptable in Java



On another hand, in Scenario 2 will compile fine and show Hello as Foo inherited Bar's greet property though Inheritance by definitions which is acceptable.

Now, adding bit complexity in it
suppose,
the class zoo is in the package com.foo now If I write following code snippet in Zoo


Foo foo = new Foo();
foo.greet;

will it be compile?

Think about it.......

The Answer is no as I said earlier by Association (different package ) you can't ever access greet. but in Same package you do.

See the relationship picture to remember the rule.

Protected access modifiers