A Bit on Super and Sub Classes Constructors and Finalizers

 

Now we revisit the Point and Circle class in slightly stripped down form while adding features for finalizing.

First we will redevelop the Point class, then we will develop the Circle class and then we will test them.

Now the code for Point.java should be copied into a new directory.

// Point.java
// Setting a point

public class Point extends Object
{
protected int x, y;

// No argument constructor
public Point()
{
// implicit call to superclass constructor occurs here
x = 0;
y = 0;
System.out.println("Point constructor: " + this);
}

// Constructor
public Point(int a, int b)
{
// implicit call to superclass constructor occurs here
x = a;
y = b;
System.out.println("Point constructor with args: " + this);
}

// Finalizer
protected void finalize()
{
System.out.println("Point finalizer: " + this);
}



// convert the point into a String representation
public String toString()
{
return "[" + x + ", " + y + "]";
}
}

This is very basic and is the basis of our next class.

 

Now we are going to extend this Point class into a subclass called Circle.

Now the code for Circle.java should be copied into a new directory.

// Circle.java

public class Circle extends Point
{
protected double radius;

// No argument constructor
public Circle()
{
// implicit call to superclass constructor
radius = 0;
System.out.println("Circle constructor: " + this);
}

// Constructor
public Circle(double r, int a, int b)
{
super(a,b); // call to superclass constructor
radius = r;
System.out.println("Circle constructor with args: " + this);
}

// Finalizer
protected void finalize()
{
System.out.println("Circle finalizer: " + this);
super.finalize();
}


// Convert the circle to a string
public String toString()
{
return "Center = " + "[" + x + ", " + y + "];" + "\nRadius = " + radius;
}
}

Now we have started getting more developed.

 

Now you want to copy the following code into a file called TestSubSuper.java in the same directory.  

// TestSubSuper.java
// Demonstrate when superclass and subclass finalizers are called

import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class TestSubSuper
{
public static void main(String args[ ])
{
Circle circle1, circle2, circle3;

circle1 = new Circle(4.5,72,29);
circle2 = new Circle(10,5,5);
circle3 = new Circle(5,10,10);

circle1 = null;
circle2 = null;
circle3 = null;

System.gc();
}
}

Now you need to execute this java application.