Tuesday, May 31, 2011

OOPS Concept-Method Overriding


Method Overriding 
If you don’t want parent class implementation for any method we can override in the child class based on our child class requirement. This concept is called Overriding.
While overriding we have to fallow rules:
1. In the overriding, the method names and arg’s must be same.
Ie. In the case of the overriding the signatures of the methods must be same
Until 1.4 version, the return types must be same. But from 1.5 version onwards covariant return types are also allowed.
Example:
class p { public Number getNumber(){} }
class c extends P{ public Number getNumber(){} }
(or)
class C extends P
{
public Byte/Short/Integer getNumber(){}
}
  • For Number class Byte/Short/Integer is co-variant return types or classes.
  • Hence in case of overriding as the return type we can keep child class objects also.
Example:
import java.io.*;
class P
{
public object m1(){ return new object; }
}
class C extends P
{
public Object m1(){ return new Object; }
}
class C extends P
{
public String m1(){ return “durga”; }
}//in 1.4 CTE saying m1() in C cannot override found:string, req:object: in 1.5 ver no CTE

2. final methods can’t be overridden.
3. private methods never participate in the in the overriding because these methods are not visible in the child classes.
4. While overriding decreasing access specifier is not allowed. Violation leads to CTE.

class P { public int m1(){} }
class C extends P { public int m1(){} }
Parent class -------------------------------- Child class
public ----------------------------------------------- public
protected ---------------------------------------- protected, public
default ---------------------------------------- default, protected ,public
private ---------------------------------------- private, default, protected, public

* While implementing any interface method, we should declare that method as public in the implemented class.(by default implements interface method is public and abstract)
* An abstract method can be overridden as abstract. The child of the original child class is responsible for the implementation.

class P{
public void m1()
{ } }//non abstract

abstract class C extends P{
public abstract m1(); }//valid abstract


5. While overriding the size of the CheckedException should not increase. There is no rule for UnCheckedExceptions.
Example: Base or parent class :
public void m1()throws IOException
Derived or child class :

public void m1()throws FileNotfoundException //valid

public void m1()throws Exception -->CTE

public void m1()throws RunTimeException //valid
  • We can override a synchronized method to non-synchronized and vice versa
  • We can override native to native to non native and vice versa.
  • We can override a non-final method to final method.
  • We can’t override a static method to non static and a non-static method to static violation leads to CTE .
  • While overriding method has to execute will be decided by JVM based on the Run Time Object. Hence Overriding is an example of “dynamic polymorphism” or “LateBinding” (Dynamic Method dispatch).
  • If the parent’s class reference can be used to hold child class object by using that reference we are allowed to call only parent class methods. Child class specific methods are not allowed to call by using parent class reference.

How to Convert an Array to a List

This piece of Java code shows how to convert an array to one of the Collection types, namely a List.
There is a class called Arrays (not to be confused with an array) that has a method called as List() which takes an array as argument and converts it to a List object. Generics can be used to specify the List elements type.

package org.best.example;

public class Main {
  
    public void arrayToList() {
      
        String[] cars = {"Dodge", "Chevrolet", "BMW", "Toyota"};
        List<String> carList = Arrays.asList(cars);

        for (String car : carList) {
            System.out.println(car);
        }
    }
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().arrayToList();
    }
}

Monday, May 30, 2011

How to Change the File Date and Time

This example shows how to change / update the date and time of a file. This is done thought the FileUtils class which is part of the Apache Commons IO library.
We can get the actual file time by using the core java.io.File class and calling its lastModified() method which returns the time as a datatype long.
The value is the number of milliseconds elapsed since January 1, 1970. To update the time we use the static touch() method of the FileUtils class which will open and close the file without modifying it, but update the file date and time.
Note that if the file that we are trying to update the time for doesn't exist, it will be created through a call to the touch() method.

The example gets the timestamp for a certain file, calls touch and then gets the timestamp again and print out whether the second timestamp was larger than (i.e. after) the first timestamp.


 package org.best.examples;

import java.io.IOException;
import org.apache.commons.io.FileUtils;

import java.io.File;


public class Main {

    public static void main(String[] args) {
        try {
            File file = new File("pic.jpg");
            long lastModified1 = file.lastModified();
            FileUtils.touch(file);
            long lastModified2 = file.lastModified();
            System.out.println("File date / time was updated: " + (lastModified2 > lastModified1));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

OOPS Concept-Method Overloading


Method Overloading

Two methods having the same name are not allowed in the case of C-language, for every data type even though the functionality in the same; we should maintain different method names. It increases the complexity of the programming. But in java, two methods having the same name is allowed irrespective of parameters. We can maintain the same method name for similar type of functionality. It simplifies the programming. Such types of methods are called Overloaded methods.
• Two methods are said to be overloaded if and only of they have the same method name, but different parameter list(at least order).
• The signatures of the two overloaded methods must be different.

Example:
public void m1(){}
private int m1(int i){}

• Here m1() & m1(int i) are overloaded. We never consider return type, access modifier and throws class in overloading.
Example:
class Sample
{
public void m1()
{
System.out.println(“no arg”);
}
public void m1(int i)
{
System.out.println(“ int arg”);
}
public void m1(double d)
{
System.out.println(“ double arg”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10.5);
}
}

• In the case of overloading which overloaded method must be executed is decided method must be executed is decided by compiler only based on reference type.
• Ie., Overloaded method resolution is the duty of compiler only. Hence Overloading is the best
ex. of static polymorphism and sometimes also known as Early Binding.

s.m1(10L);//double arg
s.m1(‘a’);//int arg

i.e., Automatic Promotion in Overloading:
• If we are calling a method m1() by passing char as arg on the sample reference then the compiler will check in the Sample class for m1(), which can take char as the arg.
• If it finds that method, it will execute at run time.If there is no such method the compile promotes that char arg to the int arg and checks for m1(int) method.
• If there is no such method, the compiler will check for m1(long), followed by m1(float),followed by m1(double). Still if the compiler won’t find any such method then only compiler will raised CTE saying ‘cannot resolve the symbol m1(char).

CASE 1:
class Sample
{
public void m1(int i,float f)
{
System.out.println(“int,float”);
}
public void m1(float i,int f)
{
System.out.println(“float,int”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(10,10.0f);//int,float
s.m1(10.0f,10);//float,int
s.m1(10,10);//invalid-> CTE:reference m1 is ambiguous
}
}
CASE 2:
class Sample
{
public void m1(String s)
{
System.out.println(“String version”);
}

public void m1(Object o)
{
System.out.println(“Object version”);
}
public void m1(double d)
{
System.out.println(“double version”);
}
public static void main(String a[])
{
Sample s=new Sample();
s.m1(“viswan”);// String version
s.m1(new Object());// Object version
s.m1(null);// String version
}
}
If there is Double (wrapper class) then CTE: reference to m1 is ambiguous.
CASE 3:
class Animal
{
}
class Monkey extends Animal
{
}
public class OLStaticBinding {

public void m1(Animal a)
{
System.out.println("Animal version");
}
public void m1(Monkey m)
{
System.out.println("Monkey version");
}
public static void main(String a[])
{
OLStaticBinding s=new OLStaticBinding();
Animal a1 =new Animal();
s.m1(a1); // Animal version
Monkey m =new Monkey();
s.m1(m); // Monkey version
Animal a2 =new Monkey();
s.m1(a2); // Animal version

}

}
}
In the case of overloading the method resolution performed by the compiler is based on the reference type.

Sunday, May 29, 2011

How do I right justified JTextField contents?

To right justified a JTextField contents we can call the setHorizontalAlignment(JTextField.RIGHT) method of the JTextField class.

package org.best.example.swing;

import javax.swing.*;
import java.awt.*;

public class TextFieldRightJustify extends JFrame {
    public TextFieldRightJustify() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 200);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));

        JTextField textField = new JTextField(15);
        textField.setPreferredSize(new Dimension(100, 20));
        
        //
        // Right justify the JTextField contents
        //
        textField.setHorizontalAlignment(JTextField.RIGHT);

        container.add(textField);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TextFieldRightJustify().setVisible(true);
            }
        });
    }
}

OOPS Concept-Method Signature


Method Signature

·      In java the method signature is compiled with method name and argument list (the order of arguments also important).
·      Return type is not part of the signature.
·      Compiler uses the method signature to resolve method calls.
·      With in a class two methods having same the signature is not allowed, violation needs to CTE saying method is already defined in class.

Example:
public void m1(int a, int b)
{
m1(int,int); -----> signature of method m1
}

Example:
public void m1(int a, float b)
{
m1(int , float); //valid
m1(float , int);//invalid
}



Example:
class Test
{
public int m1(int i){}//invalid, CTE: m1(int) is already defined in test
public void m1(int i){}
}