Friday, June 3, 2011

JAVA BASICS-Abstract Class


Abstract Class 
We can apply abstract keyword for the classes and methods .abstract keyword is not possible for variables.If method declared as abstract we don’t know implementation child class is responsible to provide the implementation for the parent class abstract methods.

Abstract public void m1(); // here ; is mandatory.

Abstract method has declaration only and should not have any implementation.
This is the way of decorating abstract method .we should not keep curly braces at end.
  • If a class contain at least one abstract method we should have to declare that class as abstract otherwise compile time error.
  • An abstract class is not compulsory to have an abstract method.i.e abstract class may contain zero number of abstract methods also.this is for restricting object creation.
  • HttpServlet class doesn’t contain any abstract methods ,still the class is declared as abstract because the methods present in HttpServlet can’t provide any request ,response for the end user ,these methods are just for sending error information.
  • It’s a good programming practice to use abstract methods ,abstract classes and interfaces.
Example:
class Sam
{
abstract void m1(); //error
}

Example 2:
abstract class Xy
{
abstract void m1(); // valid
}

Example 3:
abstract class X
{
void m1() // valid
{
System.out.println(“valid”);
}
}

Example 4:
abstract class X
{
abstract void m2();
}

class Y extends X // error we must provide the implementation for m2 method .
{
}

How to Extend the size of an array

This example shows how to extend the size of an array. Since arrays are static in size, they cannot be extended in the way collection objects can (for example a Vector). Hence we need to create a new array, add the new data and copy data from the first array. In this example we create an array with three names, then we create another array with the length of 5. We add two names to position 3 and 4 (which is really position 4 and 5 since the first element of an array has the index 0). Then we use the arraycopy() method of the System class and specify that we want to transfer data from the first position in the names array (param 1 and 2), and we want to insert the data in the array "extended" (param 3) from the first position (param 4) up to the length of the array "names" (param 5). Finally we print the elements of the extended array.

package org.best.examples;
public class Main {
   
    /**
     * Extends the size of an array.
     */

    public void extendArraySize() {
       
       
        String[] names = new String[] {"Joe", "Bill", "Mary"};
       
        //Create the extended array
        String[] extended = new String[5];
       
        //Add more names to the extended array
        extended[3] = "Carl";
        extended[4] = "Jane";
       
        //Copy contents from the first names array to the extended array
        System.arraycopy(names, 0, extended, 0, names.length);
       
        //Ouput contents of the extended array
        for (String str : extended)
            System.out.println(str);
       
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

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

Thursday, June 2, 2011

Oops Concepts - Polymorphism

Polymorphism

This refers to the ability to assume different forms. In OOP, it indicates a language’s ability to handle objects differently based on their runtime type.
When objects communicate with one another, we say that they send and receive messages. The advantage of polymorphism is that the sender of a message doesn’t need to know which class the receiver is a member of. It can be any arbitrary class. The sending object only needs to be aware that the receiving object can perform a particular behavior.

A classic example of polymorphism can be demonstrated with geometric shapes. Suppose we have a Triangle, a Square, and a Circle. Each class is a Shape and each has a method named Draw that is responsible for rendering the Shape to the screen.

With polymorphism, you can write a method that takes a Shape object or an array of Shape objects as a parameter (as opposed to a specific kind of Shape). We can pass Triangles, Circles, and Squares to these methods without any problems, because referring to a class through its parent is perfectly legal. In this instance, the receiver is
only aware that it is getting a Shape that has a method named Draw, but it is ignorant of the specific kind of Shape. If the Shape were a Triangle, then Triangle’s version of Draw would be called. If it were a Square, then Square’s version would be called, and so on.

We can illustrate this concept with a simple example. Suppose we are working on a small graphics package and we need to draw several shapes on the screen at one time. To implement this functionality, we create a class called Scene. Scene has a method named Render that takes an array of Shape objects as a parameter. We can now create an array of different kinds of shapes and pass it to the Render method. Render can iterate through the array and call Draw for each element of the array, and the appropriate version of Draw will be called. Render has no idea what specific kind of Shape it is dealing with.

The big advantage to this implementation of the Scene class and its Render method is that two months from now, when you want toadd an Ellipse class to your graphics package, you don’t have to touch one line of code in the Scene class. The Render method can draw an Ellipse just like any other Shape because it deals with them generically. In this way, the Shape and Scene classes are loosely coupled, which is something you should strive for in a good object-oriented design.

This type of polymorphism is called parametric polymorphism , or generics. Another type of polymorphism is called overloading. Overloading occurs when an object has two or more behaviors that have the same name. The methods are distinguished only by the messages they receive (that is, by the parameters of the method). Polymorphism is a very powerful concept that allows the design of amazingly flexible
Applications.

OOPS Concept-Constructors


Constructors 
The purpose of Constructor is to perform of our creted object. Whenever we are calling new operator for the creation of object, it calls constructor automatically to provide initialization for the object.
class Student
{
String name; int rno;
Student(String name, int rno) ----> Constructor
{
this.name=name;
this.rno=rno;
}
public static void main(String a[])
{
Student s=new Student(“xxx”,101);
Student s1=new Student(“yyy”,102);
-------
------
}
}

Rules Of Constructor :

1. Constructor concept is applicable for every class including abstract class also.
2. Interface doesn’t have Constructor’s concept.
3. The name of the const4ructor and the name of the class must be same.
4. The allowed modifiers for the constructors are public, private, protected, and default. If you are applying any other we will get a CTE saying “modifier xxx not allowed her”.
5. We can’t give return type for the constructor even void also.

If we will give return type for the constructor that thing as a method instead of constructor that thing as a method instead of constructor (so,there is no CTE). Ie., it is legal (but stupid) to have a method whose name same as classname.

Default Constructor:-

If the programmer is not writing any constructor, then only compiler will generate a default constructor.
Ie., either programmer written constructor or compiler generated must present in your class but not both at a time.
Prototype of default constructor shown below:

a).Programmer written code:-

Compiler generated code:-
class Test
{
Test()
{
super();
}
}
  • The default constructor is always no argument constructor.
  • The access modifier of the default constructor is sane as access modifier of the class (public & default only).
  • The default constructor contains only one statement which is ‘no arg call to super class Constructor ‘ (super();)
b) Programmer written code:-
class Test {
Test(int i)
{
System.out.println(“constructor”);
}
}

Compiler generated code:-

class Test {
Test(int i)
{
super();
System.out.println(“constructor”);
} }

c). Programmer written code:-

class Test {
Test(int i)
{
super();
System.out.println(“Hai”);
} }
Compiler generated code:- no new code is going to generate.

d). Programmer written code:-

class Test {
void Test()
{
System.out.println(“hello”);
}
}

Compiler generated code:-

class Test {
void Test()
{
System.out.println(“hello”);
}
Test()
{
super();
}
}

e). Programmer written code:-

class Test {
Test()
{
this(10);
System.out.println(“hai”);
}
Test(int i)
{
System.out.println(i);
}
}

Compiler generated code:-

class Test {
Test() {
this(10);
System.out.println(“hai”);
}
Test(int i) {
super();
System.out.println(i);
}
}
  • The first line inside a constructor must be a call to super class constructor ( by using super();) or a call to overload constructor of the same class. (by using ‘this’ keyword).
  • If you are not writing the first line as either ‘super()’ or ‘this’ then compiler will always keep a no arg call to super class constructor (super();).
1. Allowed only in Constructors.
2. Must be first statements.
3.Either super() or this, but not both.
  • We can invoke another constructor from constructor from a method violation leads to CTE. i.e, super() or this must be used inside the constructor only not anywhere else.
Overloaded Constructors:

We are allowed to keep more than one constructor inside a class , which are considered as overloaded constructors. We can’t override the constructors, because they belong to the same Ex: class Test {
Test(int i){}
Test(){} ---->Overloaded Constructors
}
  • Constructors are not inherited and hence we are not allowed to override a constructor.
  • while recursive method invocation we will get stackoverflowException But in case of constructors we will get compile time error.
  • If we are writing any constructor in our class it is recommended to place default constructor also. Otherwise we should take care while writing the constructor child case.
  • If the parent class constructor throws some Checked Exception, while writing child class constructors we should take care.In case of unchecked exception no rule.
Recursive Constructor invocation:

class Sample {
Sample() // This is a compile time problem
{
this(10);
}
Sample(int i)
{
this(); // Invalid, CTE: recursive constructor invocation
}
public static void main(String a[])
{
System.out.println(“hai”);
}
}
Constructing the Child class constructors:

Example:
class P {
P()
{ super(); }
}
class C extends P
{
C() {
super();
} } //valid

Example:
class P {
P(int i)
{
System.out.println(i);
}
}
class C extends P
{
C()
{
super(10); // valid (without super invalid)
}
}

Example: class P
{
P() throws Exception ----> checked exception
{ }
}
class C extends P
{
C() // compile time error unhandled exception type exception
{ }
}

How to Convert Boolean to String

To convert a boolean value to a String you need to use the wrapper class of the boolean datatype. It has the same name as the datatype boolean, but it begins with the captial B - Boolean. To convert a boolean value you create an instance of the wrapper class sending the boolean value as argument to the constructor. Then you simply call the toString() method which will return a String representation of the boolean value.

package org.best.examples;

public class Main {
   
    /**
     * Boolean to String conversion
     */

    public void convertBooleanToString() {
       
        boolean theValue = true;
       
        //Do the boolean to String conversion
        String theValueAsString = new Boolean(theValue).toString();
       
        System.out.println(theValueAsString);
    }
   
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

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

Wednesday, June 1, 2011

How to Extract contents of a zip file

This example shows how to extract a zipfile containing one file (or entry).  The name of the zip file is 'compressed.zip' and we want to write the contents to a file called 'extracted.txt'. We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted. After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start  reading the contents from the input stream and writing each chunk read to the output stream. As usual we should clean up properly afterwards so we close the input and output streams.

package org.best.example.compression
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {

    /**
     * Extracts a zip file
     */

    public void extractZipFile() {
       
        try {
            String zipFileName = "compressed.zip";
            String extractedFileName = "extracted.txt";
           
            //Create input and output streams
            ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
            OutputStream outStream = new FileOutputStream(extractedFileName);
           
            ZipEntry entry;
            byte[] buffer = new byte[1024];
            int nrBytesRead;
           
            //Get next zip entry and start reading data
            if ((entry = inStream.getNextEntry()) != null) {
                while ((nrBytesRead = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, nrBytesRead);
                }
            }
                   
            //Finish off by closing the streams
            outStream.close();
            inStream.close();
           
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * @param args the command line arguments
     */

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

OOPS Concept-Method Hiding


Method Hiding:-

This is exactly same as overriding except both parent & child class methods must be declared as static. In the method hiding the method resolution take care by compiler only based on the reference type.
Ex:
class P
{
static int x=10;
int y=20;
}
class C extends P
{
static int x=100;
int y=200;
}
class Sample
{
public static void main(String[] a)
{
P p=new C();
System.out.println(p.x+”,”+p.y); //10,20
C c=new C();
System.out.println(c.x+”,”+c.y); //100,200
P p1=new P();
System.out.println(p1.x+”,”+p1.y); //10,20
}
}
  • We can’t override in the child class. But if define exactly same variable in child class.
  • Variable resolutions take care by compiler only based on the reference type.