Internal Frame in Core Java

While doing my college project i find this example to be very useful to use internal frame as MDI child. It is a simple example where internal frame is made visible and invisible to make MDI possible.

//File Name JIFDemo.Java
/**
 *
 * @author prashant-lappy
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class JIFDemo extends JFrame{

 public static void main(String [] args){
 new JIFDemo();
 }

 public JIFDemo()
 {
 // Create an internal frame
 boolean resizable = true;
 boolean closeable = true;
 boolean maximizable  = true;
 boolean iconifiable = true;
 String title = "Frame Title";
 JInternalFrame iframe = new JInternalFrame(title, resizable, closeable, maximizable, iconifiable);

 // Set an initial size
 int width = 200;
 int height = 50;
 iframe.setSize(width, height);

 // By default, internal frames are not visible; make it visible
 iframe.setVisible(true);

 // Add components to internal frame...
 iframe.getContentPane().add(new JTextArea("Hello"));

 // Add internal frame to desktop
 JDesktopPane desktop = new JDesktopPane();
 desktop.add(iframe);

 // Display the desktop in a top-level frame
 getContentPane().add(desktop, BorderLayout.CENTER);
 setBounds(100, 100, 300, 300);
 setVisible(true);

 }
}

Delegation in Java

We all know that reusability is one of the special feathers of every OOPs language including Java. We can achieve reusability by reusing the same class multiple times, which can be accomplished in three ways in Java.

The first one is quite straightforward: we simply have to create object of the existing class inside another new class. This method is called composition, because of the composition of object of the existing class.

The second one is better. Here we create a new class as a type of an existing class. Actually, we will take the form of the existing class and add some code without modifying the existing class. This method is known as inheritance, which is one of the important feathers of Java.

On the third one, we have Delegation, which is not directly supported by Java, so not much mentioned anywhere. We can say it as the mixture of above two. Because we place a member object in the class we are building, as we did in composition but at the same time we expose all the methods from the member object in the new class, just like Inheritance.

Here we have a class SpaceShipControl.java, which can be expanded on another class by two ways:

//SpaceShipControl.java
class SpaceShipControl
{
    void up(int velocity){}
    void down(int velocity){}
    void left (int velocity){}
    void right(int velocity){}
    void forward(int velocity){}
    void backward(int velocity){}
    void turboboost(int velocity){}
}

Here we are extending the SpaceShipControl.java to build SpaceShip.java. Here all the method has been extended to the child class and as well as it is expanded.

class SpaceShip extends SpaceShipControl
{
    private String name;
    public SpaceShip(String name)
    {
        this.name = name;
    }
    public String toString()
    {
        return name;
    }
    public static void main(String[] args) {
        SpaceShip protector = new SpaceShip("NSEA Protector");
        protector.forward(100);
    }
}

In some cases Inheritance is not a good tool to used, this point I will try to describe in my next post. Any way in such case we will use delegation. Here the above inheritance can be achieved from delegation too.

// SpaceShipDelegation.java
public class SpaceShipDelegation
{
    private String name;
    private SpaceShipControl controls = new SpaceShipControl();
    public SpaceShipDelegation(String name)
    {
        this.name=name;
    }
    //Delegated methods
    void up(int velocity)
    {
        controls.up(velocity);
    }
    void down(int velocity)
    {
        controls.down(velocity);
    }
    void left (int velocity)
    {
        controls.left(velocity);
    }
    void right(int velocity)
    {
        controls.right(velocity);
    }
    void forward(int velocity)
    {
        controls.forward(velocity);
    }
    public void backward(int velocity)
    {
        controls.backward(velocity);
    }
    void turboboost(int velocity)
    {
        controls.turboboost(velocity);
    }
}

Here we can see that all the methods are referred to control object, and the interface is working as inheritance. However we can add more control with delegation.

Actually Java language doesn’t support delegation, but sometimes it is useful than inheritance so development tools often use it.

Ref: Thinking in Java 4th Ed

Package as a Custom tool library

We can use Package concept to create our own libraries of tools to reduce or eliminate duplication of the code. Here we have a Package example where System.out.println and System.out.printf has been replaced with alias print and printf.

package learnjava;
import java.io.*;
//Print.java
public class Print
{
    public static void print(Object obj)
    {
        System.out.println(obj);
   }
    public static void print()
    {
        System.out.println(“”);
    }
    public static void printnb(Object obj)
    {
        System.out.print(obj);
    }
//For printf() method we may refer http://www.java2s.com/
//And for argument “Object… obj” go through my previous post https://wowjava.wordpress.com/
    public static PrintStream
            printf(String format, Object… obj)
    {
        return System.out.printf(format, obj);
    }
}

Now in below example, we have imported all the static methods of above java file Print.java. Then we are using the methods and appropriate argument for those methods.

//Only uses those methods which are Static
import static learnjava.Print.*;
//PrintTest.java
class PrintTest
{
    public static void main(String[] args) {
        print(“This is just a test.”);
        int a=30;
        print(“Displaying variable “+ a);
        printf(“%s”,”Output is “);
        printf(“%f”,21.342);
    }
}

Variable argument list

While analyzing a code I found a function with argument ‘Object… args’. This was very new for me, so I tried to find the meaning of the statement. Later I found that it is used for variable argument list but only from Java SE5.

Variable argument was exist in the previous version too. As all the class is ultimately inherited from the common root class Object and call it this way:

class Test{}
public class VarArg1 {
    static void printArray(Object[] args)
    {
        for(Object obj:args)
        {
            System.out.print(obj + ” ~ “);
        }        
        System.out.println(“”);
    }
    public static void main(String[] args) {
        printArray(new Object[]{new Integer(35),new Float(23.4),new Double(33.222)});
        printArray(new Object[]{“One”,”Two”,”Three”,”Four”,”Five”});
        printArray(new Object[]{new Test(),new Test(),new Test(), new Test()});
    }
}

Output:
35 ~ 23.4 ~ 33.222 ~
One ~ Two ~ Three ~ Four ~ Five ~
Test@19821f ~ Test@addbf1 ~ Test@42e816 ~ Test@9304b1 ~

  Now from Java SE5 we may change the similar code to below one. In which we do have no any change but the way of making variable object is changes.

class Test{}

public class VarArg2 {
    static void printArray(Object.. args)
    {
        for(Object obj:args)
        {
            System.out.print(obj + ” ~ “);
        }        
        System.out.println(“”);
    }
    public static void main(String[] args) {
        printArray(new Object[]{new Integer(35),new Float(23.4),new Double(33.222)});
        printArray(new Object[]{“One”,”Two”,”Three”,”Four”,”Five”});
        printArray(new Object[]{new Test(),new Test(),new Test(), new Test()});
    }
}

Output:
35 ~ 23.4 ~ 33.222 ~
One ~ Two ~ Three ~ Four ~ Five ~
Test@19821f ~ Test@addbf1 ~ Test@42e816 ~ Test@9304b1 ~

How Java Package is useful

As we know each component of Java has special feathers. Among all Package is one of them, which is a collection of classes and interfaces grouped together as a logic unit.

There are some special feathers that a package holds. Such as:

Abstraction:
While developing large Java software we will arrange classes in a logical in a package. This can be achieved using Package. Actually we group the bunch of classes and interfaces together in a package but we behave it as a unit. For example we have imported java.util, java.awt etc many times.

Protection:
The use of package in java allows choosing which classes may be used outside the package and which one can’t. We may also give the class protection to be access and method protection to be overridden.

There are four level of protection :

  1. Public
  2. Default (friendly)
  3. Protected
  4. Private

This can be represented in package as shown in table:

Access is available to:

public

protected

default

private

All Classes

X

     

All Subclasses

X

X

   

Classes in the Same Package

X

X

X

 

The Class Itself

X

X

X

X

Convenience:
Convenience to work on team, using package programmers doesn’t need to bother about arranging and giving the name.

Name Space Control:
Two classes can have same name if they are in different package, which make programmers to not to concerned about using name already used in other package.

Comparison between two success Programming Languages, C and Java (structure, union with class)

As we all knows, Java programming language has many similarity with C and C++ programming language. Here I am trying to show the substitution of Structure and Union with class.

If we see in java, C struct construction was omitted because a class gives more than the structure do. Class special feature is the Encapsulation, which make it much better than the struc. A structure typically contains at least two fields: union and a tag.

The C union construct is most frequently used to define structure capable of holding more than one type of data. And tag is just an ordinary field used to indicate which of the possible type is held by the union. A tag is generally an enum type. A structure containing a union and a tag is sometimes called a discriminated union.

Here is an example in which the shape_t type is discriminated union that can be used to represent either a rectangle or a circle. The area function take pointer to a shape_t structure and returns its area or -1.0, if the structure is invalid.

#include<stdio.h>
#include<conio.h>
#include<math.h>
typedef enum {RECTANGLE, CIRCLE} shapeType_t;
typedef struct
{
    double length;
    double width;
}rectangleDimensions_t;
typedef struct
{
    double radius;
}circleDimensions_t;
typedef struct
{
    shapeType_t tag;
    union{
        rectangleDimensions_t rectangle;
        circleDimensions_t circle;
    }dimensions;
}shape_t;

double area(shape_t *shape)
{
    switch(shape->tag)
    {
        case RECTANGLE:
            {
                double length = shape->dimensions.rectangle.length;
                double width = shape->dimensions.rectangle.width;
                return length*width;
            }
        case CIRCLE:
            {
                double radius = shape->dimensions.circle.radius;
                return M_PI * (radius*radius);
            }
        default:
            return -1.0; //invalid tag;
    }
}
void main()
{
    shapeType_t tag;
    shape_t *shape;
    shape->dimensions.rectangle.length=10;
    shape->dimensions.rectangle.width=15;
    shape->tag=RECTANGLE;
    clrscr();
    printf(“The area is %6.2f”,area(shape));
    getch();
}

Output:
The area is 150.00

The union construct has omitted in Java because there is a much better mechanism for defining a single data type capable of representing object of various types: Subtyping . A discriminated union is really just a pallid imitation of class hierarchy.

To transform a discriminated union into class hierarchy, we define an abstract class containing abstract method for each operation whose behavior depends on the value of tag. In above example, there is only one operation, area, which is the root of the class hierarchy.

Next, we define a concrete subclass of the root class for each type that can represented by the discriminated union. In above example, the types are circle and rectangle.

Then we include the data fields to its subclass. In above example, radius is particular to circle, and length and width are particular to rectangle.

So the example goes like this:

abstract class Shape
{
    abstract double area();
}
class Circle extends Shape
{
    final double radius;
    Circle(double radius)
    {
        this.radius=radius;
    }
    double area()
    {
        return Math.PI * radius*radius;
    }
}
class Rectangle extends Shape
{
    final double length;
    final double width;
    Rectangle(double length, double width)
    {
        this.length=length;
        this.width=width;
    }
    double area()
    {
        return length*width;
    }
}
public class StructUnion
{
    public static void main(String args[])
    {
        //Circle cir = new Circle(0);
        Rectangle rec = new Rectangle(15,10);
        System.out.println(“The area is ” + rec.area());  
    }
}

 

Reference from: Effective Java, Joshua Bloch

New static methods in JDk6 Part-1

I have been watching the different math methods that are newly released in JDK6. I had found that JDK6 add more static methods. For each given method, there is float method (i.e. if there is “double copySign(double magnitude, double sign)” then there is “float copySign(float magnitude, float sign)” too).

Among all, I have observe process of the Math.copySign() method. Math.copySign()  method sets the sign of the second argument to the sign of first argument. (i.e. (sign of b) + a => c)

Example goes like this:

class CopySignDemo
{
    public static void main(String str[])
    {
        int a=10,b=-1;
        double c = Math.copySign(a,b);
        System.out.println(“(sign of b) + a => c => ” + c);
    }
}

Out Put:
(sign of b) + a => c => -10.0

But rather I found that, this can be easily replaced by a function. Whatever the Math.copySign() is doing in above function, we can create a local function for same purpose.

So, Example goes like this:

class CopySignDemo
{
    public static void main(String str[])
    {
        int a=10,b=-1;
        double c = copySign(a,b);
        System.out.println(“(sign of b) + a => c => ” + c);
    }
    public static double copySign(double magnitude, double sign) {
        if (magnitude == 0.0) return 0.0;
        else if (sign < 0) {
          if (magnitude < 0) return magnitude;
          else return -magnitude;
        }     
        else if (sign > 0) {
          if (magnitude < 0) return -magnitude;
          else return magnitude;
        }
        return magnitude;
    }
}

 

Output:
(sign of b) + a => c => -10.0