Tuesday, 6 August 2013

Why Interface methods are Public ?


Do you know why methods are Public in Interface ?

/*
 * @Author Manoj
 * Interface with two method
 */

interface IMyInterFace{
    public void display();
    public void calculate();
}



//Implementation Class
class MyImplClass implements IMyInterFace{   
   
   
    //Interface Method
    public void display(){
        System.out.println("Hi: Override-Display");
    }
   
    //private void display(){
    //    System.out.println("Hi: Override-Display with Private");
    //If you run this method then, Error Weaker Access Privileges
    //}
   
    //Interface method
    public void calculate(){
        System.out.println("Hi: Override-calculate");
    }
   
    //Class Method
    public void show(){
        System.out.println("Hi: I am Own Method");
    }
   
    public static void main(String str[]){
        IMyInterFace f=new MyImplClass();
        f.display();
    }
}


Output:- Hi: Override-Display




Explanation :-

In the above example , Interface methods are public means extremely strong access.When , you try to access those public method with private or protected (weak access privilege than public) then, you will face error.So, I override those two interface methods with same strong access privilege (public).
Please know more about strong/weak access privilege.

As you know ,objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world.So, the most common form, an interface is a group of related methods with empty bodies.

When you are creating an Interface, you must have to declare the methods as Public inside the interface.When you are creating an Interface , it means you are creating a common schema/structure and you are going to implement over any class (Known as Implementation Class). If you need more interesting points about Interface then , Click.


But , our point is why all methods are public in interface.Because of  weaker access privileges.Interface means you are going to implement those methods in implementation classes.So, that interface method can accessed by any where , only require to implementing that Interface.When you are declaring a method(Without body) inside interface  , by default you are making that method with the most strong access privileges (public).

  1. Do you really know , what is weaker access privilege ?
  2. Are you really interested on Interface ?
  3. What is Access Specifier when Overriding ?







Hope it will help you.
Any suggestions or comments will appreciated.

Wednesday, 31 July 2013

Attempting to assign weaker access privileges - Error in Java

As per the rule in overriding , you cannot apply weaker access specifier over a stronger access specifier.Suppose , your parent class has a method Display() with stronger access specifier like Public, then you cannot use weaker access specifier like private or public when you are overriding the Display() method.

Note :-

 Public is the 1st stronger access specifier
 Protected is the 2nd stronger access specifier
 Default is the 3rd stronger access specifier
 Private is the most weaker access specifier

 Always keep in mind about the access specifiers has vital role in inheritance (OOPS concept).

 Example :-

 /*
 * @Author Manoj
 *
 */


class AccessTest{
    protected void display(){ //Stronger Access specifier
        System.out.println("Hello AccessTest:Display");
    }
}

class TestWithMain extends AccessTest{
    // I am trying to override with weaker specifier , it show error
    // You can use public or protected (higher or same level of access specifier)
    private void display(){
        System.out.println("Hello TestWithMain:display");
    }   
    public static void main(String str[]){       
        AccessTest acObj=new TestWithMain();
        acObj.display();
    }   
}

 
 Error :-

 TestWithMain.java:8: display() in TestWithMain cannot override display() in AccessTest;
 attempting to assign weaker access privileges; was protected
    private void display(){

   

So, now if you change the access specifier to protected or public then it will work properly.

Changed executable code :-

    public void display(){
        System.out.println("Hello TestWithMain:display");
    }

   
    OR
   
    protected void display(){
        System.out.println("Hello TestWithMain:display");
    }

   

Hope it will help you.

Access Specifier in Method Overriding

As per the rule in overriding , you cannot apply weaker access specifier over a stronger access specifier.Suppose , your parent class has a method Display() with stronger access specifier like Public, then you cannot use weaker access specifier like private or public when you are overriding the Display() method.

Note :-

 Public is the 1st stronger access specifier
 Protected is the 2nd stronger access specifier
 Default is the 3rd stronger access specifier
 Private is the most weaker access specifier

 Always keep in mind about the access specifiers has vital role in inheritance (OOPS concept).

 Example :-

 /*
 * @Author Manoj
 *
 */


class AccessTest{
    protected void display(){ //Stronger Access specifier
        System.out.println("Hello AccessTest:Display");
    }
}

class TestWithMain extends AccessTest{
    // I am trying to override with weaker specifier , it show error
    // You can use public or protected (higher or same level of access specifier)
    private void display(){
        System.out.println("Hello TestWithMain:display");
    }   
    public static void main(String str[]){       
        AccessTest acObj=new TestWithMain();
        acObj.display();
    }   
}

 
 Error :-

 TestWithMain.java:8: display() in TestWithMain cannot override display() in AccessTest;
 attempting to assign weaker access privileges; was protected
    private void display(){

   

So, now if you change the access specifier to protected or public then it will work properly.

Changed executable code :-

    public void display(){
        System.out.println("Hello TestWithMain:display");
    }

   
    OR
   
    protected void display(){
        System.out.println("Hello TestWithMain:display");
    }

   

Hope it will help you.

Monday, 29 July 2013

How to inherit a constructor in JAVA

First of all when we are talking about the inheritance , Java does not inherit the construtor from super class.As we know constructor is one of the member of a , but we cannot inherit it for sub class (child class).Yes, we can invoke a super class (parent class) constructor from sub class by using the keyword "super".

Few Points about 'super' Keyword :-

1. Its a reserved keyword by Java API.
2. It is used to invoke or call super class (parent class) members .
3. When 'super' keyword is used inside the sub class (child class) constructor , 'super' keyword
     is the first line inside the constructor.

Example :-

/*
 * @Author Manoj
 * 29/07/2013
 */

class SUP{
    public SUP(String s){
        System.out.println("Hi Super: "+s);
    }
}


//SUB class extending SUP class
class SUB extends SUP{
    public SUB(String p){
        // Explicitly call the super class argument constructor
        // super is the first line inside the constructor
        super(p);
        System.out.println("Hi SUB: "+p);   
    }
   
    public static  void main(String str[]){
        new SUB("Manoj Kumar");
    }
}





OutPut :-



Hi Super: Manoj Kumar
Hi SUB: Manoj Kumar

Note :- If super class(parent class) constructor is a no-argument constructor the no need to call that constructor by using 'super'
keyword inside the sub class (child class) constructor .

When you invoke sub class (child class) constructor with no-argument, automatically super class (parent class) no-argument constructor
called or invoked.

Hope it will help you.

Friday, 26 July 2013

How do I default printer service in java ?


Code :


package experiment.java.printing;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

public class getDefaultPrinter{
    public static void main(String str[]){
        try{
        //Get print server as your local setting ( Printer)
        PrintService services = PrintServiceLookup.lookupDefaultPrintService();          
        System.out.println("Default Printer Name ::"+services.getName());
       
    }catch(Exception e){
        System.out.println("Error in get Default Printer service::"+e);
       
    }
       
    }
   
}


Example of Enumeration in java

import java.util.Enumeration;
import java.util.Vector;

/*
    Example of Enumaration with Vector
    @Author Manoj
*/

class MyEnumaration{
    public static void main(String str[]){
        Vector<String> vtr=new Vector<String>();
        vtr.add("Hi");
        vtr.add("Tester");
        vtr.add("How");
        vtr.add("Are");
        vtr.add("You?");
        Enumeration enumobj=vtr.elements();
        while(enumobj.hasMoreElements()){
        System.out.println(enumobj.nextElement());
           
        }
       
    }
}

OUTPUT:-


Hi
Tester
How
Are
You?


Read more about Enumeration.

Tuesday, 2 July 2013

hashCode() in Java

public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. The general contract of hashCode is:
  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Tuesday, 23 April 2013

Experienced Java/J2EE interview questions by MNC

Experienced Java/J2ee Interview questions asked by MNC.



1. Why main() in java is declared as public static void main? What if the main method is declared as
private?


Ans : Because, every program start exucution from main function.The static method can directly call without createing the object of the class.So, before createing object the main function runs and then it creates object.

And, public in main method due to access by JVM. If the method is private then JVM cannot call that function.The program will compile but never run.It show the message  "Main method not public."


2.What is Externalizable?

Ans : This interface is used for serialization.To save the state of an object in file. It provides two method
readExternal() and writeExternal().

3.What modifiers are allowed for methods in an Interface?
Ans : abstract and public

4.What are the different identifier states of a Thread?

Ans :
R- Running or Runnable
S- Suspended
MS- Thread Suspended on Moniter lock
MW- Thread waiting on moniter
CW- Thread waiting on condition variable


5.What are some alternatives to inheritance?

Ans : Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

6.Why isn’t there operator overloading?

Ans : Because C++ has proven by example that operator overloading makes code almost impossible to maintain.

7.What does it mean that a method or field is “static”?

Ans : Static method or field are member of class.They do not need any object for call or access . We can directly call the static method and fields without using the object.




Thursday, 7 March 2013

How to find days difference between two given dates ?

Find number of days between two given dates:-

public class FindDays {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String str1="20/01/2013";
        String str2="28/03/2013";       
        Calendar cal=Calendar.getInstance();
        cal.set(Integer.parseInt(str1.substring(6)),Integer.parseInt(str1.substring(3,5))-1,Integer.parseInt(str1.substring(0,2)));
        long xTime=cal.getTimeInMillis();
        cal.set(Integer.parseInt(str2.substring(6)),Integer.parseInt(str2.substring(3,5))-1,Integer.parseInt(str2.substring(0,2)));
        long xTime2=cal.getTimeInMillis();
        System.out.println("Final Days...."+((xTime2-xTime)/(1000*60*60*24)));

    }

}


//Out put- Final Days.... 8