Sunday, December 29, 2013

Abstract class - Why?

Inheritance allows us to create general classes which can be plugged to other classes by using an extends keyword. Let us take a simple example to create classes for variety of shapes.

public class Shape {
    double dim1, dim2;
    Shape(){}
    Shape(double d1, double d2){
        dim1=d1;
        dim2=d2;
    }
    void setDim1(double d1){
        dim1=d1;
    }
    void setDim2(double d2){
        dim2=d2;
    }
    double getDim1() {
        return dim1;
    }
    double getDim2() {
        return dim2;
    }
    void show() {
        System.out.println(getDim1()+","+getDim2());
    }
    public void calcArea(){
        System.out.println("Cannot calculate Area : Shape Unknown");
    }
}

Shape is a general class which can provide common functionality to all types of Shape classes. Let us create a Rectangle Shape

public class Rectangle extends Shape{
    Rectangle(double d1, double d2) {
        super(d1,d2);
    }
    Rectangle(){
       
    }
   public void calcArea() {
       System.out.println("area of rectangle is : "+dim1*dim2);
    }
  
   public void showPerimeter(){
       System.out.println("Perimeter = "+(2*(dim1+dim2)));
   }
}

Let us create another shape, Triangle.

public class Triangle extends Shape{
     Triangle(double d1, double d2) {
        super(d1,d2);
    }
     Triangle() {
        
     }
    public void calcArea(){
        System.out.println("area of traingle = "+(0.5*dim1*dim2));
    }
    public void draw(){
        System.out.println("draw Triangle will be implemented later");
    }
}

Rectangle and Triangle classes override calcArea() method. It makes sense to redefine calcArea(). Both, Rectangle and Triangle Shapes are well defined and so are their functionalities. Let us create a ShapeTester class to test the functionality.

public class ShapeTester {
    public static void main(String[] args) {
        Shape shape= new Shape(20,50);
        Rectangle rectangle = new Rectangle(30,40);
        Triangle triangle = new Triangle(25,12);
        shape.calcArea();
        rectangle.calcArea();
        triangle.calcArea();
    }   
}

run:
Cannot calculate Area : Shape Unknown
area of rect is : 1200.0
area of traingle = 150.0

calcArea() method is insignificant in Shape class. The question is, when there is no well defined functionality for calcArea() method in Shape class we can do two things :

First, we can remove the error message and leave the method with null body.

        public void calcArea(){ }

If calcArea() is null body method, it is misleading. When the method will be called nothing happens.

Second, we can remove the calcArea() method from the Shape class. It seems to be a good alternative. But if we want to design a family of classes with common behavior,  where every type of Shape is capable of calculating the area, depending on the Shape type, we need to find another alternative to deal with the calcArea() method. This is what we can do. We will create calcArea() method in Shape class without any definition. Such a method is called an abstract method. When a class contains one or more abstract methods, class must be declared abstract.

public abstract class Shape {
    double dim1, dim2;
    Shape(){}
    Shape(double d1, double d2){
        dim1=d1;
        dim2=d2;
    }
    void setDim1(double d1){
        dim1=d1;
    }
    void setDim2(double d2){
        dim2=d2;
    }
    double getDim1() {
        return dim1;
    }
    double getDim2() {
        return dim2;
    }
    void show() {
        System.out.println(getDim1()+","+getDim2());
    }
    public abstract void calcArea(){
        System.out.println("Cannot calculate Area : Shape Unknown");
    }
}

Shape class is abstract as it does not define all its methods. An abstract class is incomplete and hence cannot be instantiated. It can only be used as a super class. Any subclass of an abstract class needs to override all the abstract methods in the super class to become a concrete class. If subclass does not override all the abstract methods of its super class(es), subclass remains as an abstract class and hence cannot be instantiated. Abstract methods help to enforce certain functionality in the subclasses. Sometime, even if we have a concrete class and we wish it to be used only as a super class. We can create an abstract class, which does not contain any abstract method. For example :

public class abstract Shape {
    double dim1, dim2;
    Shape(){}
    Shape(double d1, double d2){
        dim1=d1;
        dim2=d2;
    }
    void setDim1(double d1){
        dim1=d1;
    }
    void setDim2(double d2){
        dim2=d2;
    }
    double getDim1() {
        return dim1;
    }
    double getDim2() {
        return dim2;
    }
    void show() {
        System.out.println(getDim1()+","+getDim2());
    }
    public void calcArea(){
  }
}


Now, although we have all the well defined or implemented methods in Shape class, Shape class cannot be instantiated, as it is declared as an abstract class. A class can be declared abstract if we wish to avoid instantiating the class. Such a class can only be used for subclassing. 

By Nancy 
@ 1:55 am 12/30/2013

Thursday, December 12, 2013

NB7.3.1 and GF4.0 --- How to Get JavaDB Work?

I installed NetBeans 7.3.1 with GlassFish 4.0 on Windows 7 platform. Wrote web Application and as I try deploying , it gave two problems.

1. I could not start Java DB(Derby Database). I had previous install at a different location, that was one reason. Java DB start option was disabled.
Fix :
  • In NetBeans IDE
    • Select the Services Window -> databse
    • Expand the Database Node
    • Select Java DB, click RMB (Right Mouse Button) and select Properties
    • Specify the folder where Java DB is installed (GlassFish install location\javadb) and Click OK
    • Java DB server will start now



2.  GlassFish Server did not start, error message "GlassFish Server 4.0 cannot start port is occupied" was displayed in error dialog box.

Fix:

  • To check for busy ports
    • Open Command window Start -> Run -> cmd
    • At the command prompt 
      • netstat -aon
      • it showed port 8080 busy


    • In NetBeans IDE Services Window
      • Expand Server Node
      • Select GlassFish Server, Click RMB and select Properties
      • Look for the Domain Folder











      •  Note down the path of Domain folder
      • In windows explorer fo to the folder specified in the Domains Folder
      • domains folder will have domains1\config which has domain.xml file
      • open C:\glassfish-4.0\glassfish\domains\domain1\config\domain.xml file in an editor
      • search for 8080 and replace it with desired port

      • Save the edited file
      •  Currently present GlassFish server in NetBeans is configured to listen on port 8080
      • Remove this server from NetBeans
        • Select the GlassFish Server in NetBeans Services window, click RMB and select Remove
      • To add newly configured Server
      • Select Servers node in Services window
      • Click RMB and select Add Server
      • In Choose Server Window, select GlassFish Server and click Next Button
      • In Server Location Window, click browse button and select GlassFish installation directory, in this case it is C:\glassfish-4.0 and click Next Button
      • In Domain Location Window, accept the default values and click Finish
      • GlassFish server has been added to netBeans with newly configured port to listen
      • Start the Server... Enjoy !!!
      • Its Up and Running :)
Posted @ 6:19 pm 12/12/2013

Thursday, January 31, 2013

Understanding Java - while Loop



While Loop

It executes a code block while the Boolean expression remains true. 

Syntax :   while ( booleanExpression ) {
                          code block
                  }

Points to Ponder :
  1. Variable used in the Boolean expression must be initialized before the while statement.
  2. There must be valid condition test to stop, otherwise it becomes an infinite loop
  3. There must be a statement in the loop to modify the variable which controls the condition


'n' is a local variable and hence needs explicit initialization. Java compiler flags an error.




'n' needs to be initialized. Here is the second code( Example of Inifinite Loop )


















Due to no change in the value of variable 'n',  it keeps printing 1.


Proper while Loop Example :






Any boolean value true can be used instead of boolean expression. If true is used in while, it behaves as infinite loop. To stop this loop, break statement can be used.



Now here is something very special about the nature of while


Java compiler does not allow the use of false literal in the condition/boolean expression. A smart compiler :). It flags a compile time error "unreachable code".  But here is something more wonderful about Java compiler.


Variable with value false is allowed... :)