Wednesday, October 3, 2012

Java Tidbits ....................5(Covariant)

  •  An overriding method, should define exactly same set of argument list, as the overridden method, or else we will end up defining an overloaded method. This includes the covariant data types, i.e., if any argument in the overriding method is a subclass of the argument defined in the super class, we will end up defining an overloaded method.
  •  A valid overriding method can define a return type, which is a subclass of the return type defined by the Overridden method in the super class. 
Run this example  and tweak your brain.
---------------------------------------------------------------------------------
class TestB{
    int kk=9;
    public  Object mytest(Object o)
    {
        System.out.println("ok in Base");
        return o;
    }
}

public class TestA extends TestB{
   
    int kk =8;
   
    public  String mytest(Object o )
    {
        System.out.println("ok in overloaded sub class");
        return o.toString();

    }
    public  void mytest(String o )
    {
        System.out.println("ok in sub class");

    }
    public static void main(String args[])
    {
      
        TestB tb = new TestB();
        TestA ta = new TestA();

        
        ta.mytest("ok");
        tb.mytest("ok");
        System.out.println(" ta.kk = "+ ta.kk + "tb.kk = "+tb.kk);
      
        tb = new TestA();
        tb.mytest("ok");
        System.out.println("tb.kk = "+tb.kk);

      
        System.exit(0);

     }
} 
For more examples on covariant types refer >>
http://cafe4java.com/mockexams/scjp/mock1/q1.php

Monday, October 1, 2012

Java Tidbits ............................4(enum)

  • Enums are special classes whose fields are constants.
  • Enum can be declared either inside of a class or as separate class.
  • When outside a class Enum can either be public or default access modifier. By default nested enum are static ( ie inside class ).
  • In Enum definitions the enum constants must be declared before any other declarations in an enum type. ( compile error will be thrown if it is occurs )
  • Enum cannot be declared inside methods .why ? ( because methods cannot have class ) 
  • ; colon is optional to be placed at end of enum syntax.
  • Enum cannot be invoked via new operator .
  • Like classes Enum can have multiple argument constructor or may have overloaded constructors  .
  • Like classes Enum can have methods definitions.
  • Enum can  provide constant specific class body ie : a particular constant can override one or more  of its methods .
  • Enum are implicitly Serialiazable and comparable and extends Enum abstract class , so enum can be  serialized and can be put into  ordered collection.
  • If there is any abstract method declared inside enum class then each of its enum type must have to provide its definition.
  • Abstract & Final Enum cannot be defined.
  • equals(), compareTo(), finalize() methods are final . it cannot be overridden.
  • Enum can implement interfaces but cannot extends any other class. 
  • Enum cannot be of Generic Type.
Practice few Enum from K & B book .

http://www.ejavaguru.com/scjp5freemockexam.php#enumq9

Generics aren't so generic !

Generics in Java 5 enables Types(class/interface) to  have parameters when defining classes, interfaces and methods.A generic type is a type with formal type parameters. While A parameterized type is an instantiation of a generic type with actual type arguments.

A generic type is a reference type that has one or more type parameters. These type parameters are later replaced by type arguments when the generic type is instantiated (or declared )

If the compiler erases all type parameters at compile time, why should you use generics?

1) To provide compile time casting.
2) Elimination of casts
3) Enabling programmers to implement generic algorithms. ..( more later )

******UpperBound WildCards
ex:
List <  ? extends Number >

take method
public static double sumOfList(List < ? extends Number > list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}


here both
List < Integer >  li = Arrays.asList(1, 2, 3);
List < Double > li = Arrays.asList(1.1, 2.1, 3.1); 
can substitute at compile time.


******LowerBound WildCards 


public static void addNumbers(List < ? super Integer > list) {
    for (int i = 1; i <= 10; i++) {
        list.add(i);
    }
}
 
Here only  
List < Integer > li = Arrays.asList(1, 2, 3);
or List < Number > li = Arrays.asList(1, 2, 3); 
can be passed at compile time.
Since Integer or any of its super class is allowed .

More explanation on Generic Types is given at

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html

Friday, September 28, 2012

Java Tidbits ........................3 (Serialization)

  • A class that needs to be serialized must implement  marker interface Serializable.
  • A class can extends a base class that doesn't implement Serializable .
  • A class if  contains or has-a relation with any of such  instance variable that doesn't implement Serializable will throw runtime exception while serializing . [ ..java.io.NotSerializableException ..]
  • If the base class doesn't implement Ser then in that case  while deserializing object the constructor of base class is called again while the transient and static variables of object will be intialized to default and recent vale respectively .
Try running below example 

import java.io.*;

class Player {
Player() { System.out.print("p"); }
}
public class CardPlayer  extends Player implements Serializable{
// Player p =new Player (); this can be commented to check Has-A relation ship 
CardPlayer() { System.out.print("c"); }
public static void main(String[] args) {
    CardPlayer c1 = new CardPlayer();
try {
             FileOutputStream fos = new FileOutputStream("play.txt");
             ObjectOutputStream os = new ObjectOutputStream(fos);
             os.writeObject(c1);
             os.close();
            FileInputStream fis = new FileInputStream("play.txt");
            ObjectInputStream is = new ObjectInputStream(fis);
            CardPlayer c2 = (CardPlayer) is.readObject();
            is.close();
} catch (Exception x ) { System.out.println("here ") ; x.printStackTrace();}
}
}

Thursday, September 27, 2012

Java Tidbits ............................2 (Finally)


will finally execute when return / System.exit(0) is invoked in try or catch block?

Yes . with return finally block will execute before returning the value but with System.exit(0) it immediately quits JVM so no point of execution any furthur 

------------------------------------------------------------------------------------------

BEWARE , Finally is not guaranteed to complete ! It all depends on user's implementation.
see below example ::


public class OverAndOver {
 static String s = "";
 public static void main(String[] args) {
 try {
 s += "1";
     throw new Exception();
   } catch (Exception e) { s += "2";
     } finally { s += "3"; doStuff(); s += "4";
     }
 System.out.println(s);
 }
 static void doStuff() { int x = 0; int y = 7/x; }
 }


Wednesday, September 26, 2012

Java Tidbits ............................1

Can one extends multiple interfaces in java ?


interface A {

void doStuffA();
}

interface B {

void doStuffB();
}

interface C extends A,B  {
void doStuffC();
}

// Is C valid interface ?
Yes ! it is because interfaces are not classes ....... 

 -------------------------------------------------------------------------------------------


Monday, September 3, 2012

To Extend or to Implement

This is the most basic question that i never been able to understand until i made a program in which i started a  thread twice .

The answer that novice programmer give is
1) a Java class can have only one superclass. So if your thread class extends java.lang.Thread, it cannot inherit from any other classes. This limits how you can reuse your application logic.

correct !!
Now when same question is asked to an exp programmer then some more reason is expected  .
The reason is

2) Once a thread is  finished with its task ie: comes out of run method and cannot be restarted . Thread instance is subjected to garbage collection. So in order to resubmit the task again at some point then implementing interface is required. Also  the task can be submitted for a later point of execution .


From a design point of view, there should be a clean separation between how a task is identified and defined, between how it is executed. The former is the responsibility of a Runnable impl, and the latter is job of the Thread class.