Tuesday, 24 June 2014

Why java is not supporting multiple inheritance

- - First reason is ambiguity around Diamond problem occurs.

- - multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc 

- - Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.



Example :
   
  1. class A{  
  2. void msg(){System.out.println("Hello");}  
  3. }  
  4.   
  5. class B{  
  6. void msg(){System.out.println("Welcome");}  
  7. }  
  8.   
  9. class C extends A,B{//suppose if it were  
  10.    
  11.  Public Static void main(String args[]){  
  12.    C obj=new C();  
  13.    obj.msg();//Now which msg() method would be invoked?  
  14. }  
  15. }  

How to convert String to Number in java program

To convert a string into an int, use:
String str = "1234";
int num = Integer.parseInt(str);
To convert a number into a string, use:
int num = 1234;   
String str = String.valueOf(num);

Why there are no global variables in Java?

- -   The global variables breaks the referential transparency

- -   Global variables creates collisions in namespace.
- -  Global variables are usually a design flaw.
- - Your components should be self-contained and should not need any global state.
Instead, use private static fields.
- - Global variables (in the Java context - public static variables) are bad, because:
  • harder to maintain - you can't put a breakpoint or log each change to a variable, hence unexpected values at runtime will be very hard to track and fix
  • harder to test - read Miško Havery's post
  • harder to read - when someone sees the code he'll wonder:
    • where does this come from?
    • where else it is read?
    • where else it is modified?
    • how can I know what's its current value?
    • where is it documented?
To make one clarification that seems needed - variables != constants. Variables change, and that's the problem. So having a public static final int DAYS_IN_WEEK = 7 is perfectly fine - no one can change it.