Home

Introduction to Built-In Classes

 

The Common Object of Java Classes

 

Introduction

To assist you with creating applications, you can use an impressive library of classes available for the Java language. As you may have realized by now, everything in a Java application must belong to a class. This means that, at a minimum, you must always start an application by creating a primary class and that class would contain a method named main. Besides that class, if necessary, you can create additional classes that you judge necessary for your application.

To provide a common functionality to all classes used in an application, the Java language has a class named Object. This class is central to anything you do in an application. In fact, any class you create or use is directly or indirectly derived from Object. This means that, even if create a class that is not derived from any other class, that class is automatically derived Object. This also means that:

public class Person {

}

is the same as:

public class Square extends Object {

}

Still, if you want, when creating a class, you can explicitly derive it from Object.

Practical LearningPractical Learning: Introducing the Object Class

  1. Start NetBeans if necessary.
    To start a new application, on the main menu, click File -> New Project...
  2. In the Categories section, make sure Java is selected.
    In the Projects section, make sure Java Application is selected.
    Click Next
     
    New Project
  3. Set the Project Name to Geometry7
  4. In the Create Main Class text box, replace Main with Central and click Finish
  5. To create another package, in the Projects window, under Geometry7, right-click Source Packages -> New -> Java Package...
  6. Set the Name to Foundation and press Enter
  7. To create a class to associate to the new package, in the Projects window, right-click Foundation -> New -> Java Class...
  8. Set the Name to Point and click Finish
  9. To create a default constructor, in the Code Editor, right-click somewhere under Point and click Insert Code...
  10. In the menu that appears, click Constructor...
     
    Code Editor
  11. In the Code Editor, right-click somewhere under the StoreItem line and click Insert Code...
  12. In the menu that appears, click Getter...
  13. In the Generate Getters dialog box, click the check box of itemNumber
     
    Generate Property
  14. Click Generate
  15. To add a read/write property, right-click somewhere under the Point line and click Insert Code...
  16. In the menu that appears, click Add Property...
  17. In the Generate Getters dialog box, change the Name to x
  18. Change the Type to int.
    Accept the protected radio button.
    Accept the generate Getter and Setter radio button
     
    Add Property
  19. Click OK
  20. To create another constructor, in the Code Editor, right-click somewhere inside the class and click Insert Code...
  21. In the menu that appears, click Constructor...
  22. In the Generate Constructor dialog box, click the check box of x and click Generate:
     
    package Foundation;
    
    public class Point extends Object {
        protected int x;
    
        public Point() {
        }
    
        public Point(int x) {
            this.x = x;
        }
        
        /**
         * Get the value of x
         *
         * @return the value of x
         */
        public int getX() {
            return x;
        }
    
        /**
         * Set the value of x
         *
         * @param x new value of x
         */
        public void setX(int x) {
            this.x = x;
        }
    }
  23. Save the file
 
 
 

Creating an Object

So far, to declare a variable, we could use the name a known primitive type, initialize the variable, and use it as we saw fit. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	int number = 48.62;

        System.out.println("Number: " + number);
    }
}

As mentioned in the previous section, all classes, and subsequently all types, are based on the Object class. Because of (or thanks to) this, you can use the Object class to declare a variable of any type. Here is an example:

public class Exercise {
    public static void main(String[] args) {
	Object number = 48.62;

        System.out.println("Number: " + number);
    }
}

This would produce:

Number: 48.62`

Both programs would produce the same result because both declarations have the same effect.

Destroying an Object

In the same way, in previous sections, to use a class, we declared a variable for it, initialized it and used it as necessary. Here is an example:

class Square {
    public double side;
    
    public Square(double part) {
	side = part;
    }

    public double calculatePerimeter() {
	return side * 4;
    }

    public double calculateArea() {
	return side * side;
    }
}

public class Exercise {
    public static void main(String[] args) {
	Square sqr = new Square(48.62);

        System.out.println("Square Characteristics");
	System.out.printf("Side:      %.3f\n", sqr.side);
	System.out.printf("Perimeter: %.3f\n", sqr.calculatePerimeter());
	System.out.printf("Area:      %.3f\n", sqr.calculateArea());
    }
}

This would produce:

Square Characteristics
Side:      48.620
Perimeter: 194.480
Area:      2363.904

When an object has been created, it uses memory (and resources). When it is not used anymore, its memory must be freed so that other applications can access that memory. In other words, the object must be destroyed. Normally, this is done automatically when the compiler (the garbage collector) judges it necessary. To support this functionality, the Object class is equipped with a method named finalize. Its syntax is:

protected void finalize();

As you can see, this method is marked as protected. If  you want, when creating a class, you can override this method. Here is an example:

class Square {
    public double side;
    
    public Square(double part) {
	side = part;
    }

    public double calculatePerimeter() {
	return side * 4;
    }

    public double calculateArea() {
	return side * side;
    }

    public void finalize() {
	
    }
}

public class Exercise {
    public static void main(String[] args) {
	Square sqr = new Square(68.592);

        System.out.println("Square Characteristics");
	System.out.printf("Side:      %.3f\n", sqr.side);
	System.out.printf("Perimeter: %.3f\n", sqr.calculatePerimeter());
	System.out.printf("Area:      %.3f\n", sqr.calculateArea());

	sqr.finalize();
    }
}

In reality, to effectively override this method, you should know something about exception handling (next lesson).

Comparing Two Objects for Equality

When you declare and initialize two variables, one of the operations you may want to subsequently perform is to compare their values. To support this operation, the Object class is equipped with a method named equals. The equals() method uses the following syntax:

public boolean equals(Object obj);

This method is called from a declared variable and you must pass the other object as argument. To use this method, you should override it in your class.

Practical LearningPractical Learning: Overriding the Object.equals() Method

  1. In the Code Editor, right-click Point and click Insert Code...
  2. In the menu that appears, click Override Method...
  3. In the Generate Override Methods dialog box, click the check box of equals
     
    Generate
  4. Click Generate

Converting an Object to a String

To allow you to convert an object to a string, the Object class provides a method named toString. It syntax is:

public String toString();

To use this method, you should override it in your class. Then you can call it where a variable of the class has been declared. Once the toString() method has been overridden, you can just use the object wherever it should be treated as a string. This means that you do not have to call its toString implementation.

Practical LearningPractical Learning: Overriding the Object.toString() Method

  1. In the Code Editor, right-click Point and click Insert Code...
  2. In the menu that appears, click Override Method...
  3. In the Generate Override Methods dialog box, click the check box of toString and click Generate

Built-In Classes of Primitive Types

 

Introduction

To provide an enhanced support for primitive types, a class was created for each of them.

Character Values

To support characters, a class named Character was derived from the Object class. The Character class is defined in the java.lang package.

Boolean Values

To support Boolean values, a class named Boolean was derived from the Object class.

Numeric Values

Java has an extensive support for numbers. To make it possible, a class named Number was derived from Object. Based on this Number class, the following classes were derived:

Primitive Equivalent java.lang Class
byte Byte
short Short
int Integer
long Long
float Float
double Double

Each of these classes is based on the Number class that is derived from the Object class. All these classes are part of the java.lang package.

Each Number-based class provides a method that can be used to convert its value to the primitive equivalent. These methods are:

Primitive java.lang Class Conversion to the Primitive Type Returns
byte Byte byteValue() byte
short Short shortValue() short
int Integer intValue() int
long Long longValue() long
float Float floatValue() float
double Double doubleValue() double

Each Number-based classes is equipped with two constants named MIN_VALUE and MAX_VALUE. The MAX_VALUE constant represents the highest value that a variable declared from that class can bear. The MIN_VALUE constant represents the lowest value that a variable declared from that class can bear.

Each Number-based class overrides the toString() and the equals() methods of their ancestor the Object class. Te overridden toString() method makes it possible to use a variable declared from their class as a string. The equals() method makes it possible to compare two variables declared and initialized from the same class.

Parsing a String

So far in previous lessons, to retrieve a value from a primitive type, we were using the Scanner class. Each Number-based class is equipped with a method that can be used to retrieve a value from the user and convert it to the value based on the class.  These methods are:

Primitive java.lang Class Method Parser Returns
byte Byte parseByte(String str) byte
short Short parseShort(String str) short
int Integer parseInteger(String str) int
long Long parseLong(String str) long
float Float parseFloat(String str) float
double Double parseDouble(String str) double

Value Comparisons

One of the most common operations performed on variables consists of comparing their values: to find out whether they are equal or to know whether one is higher than the other. These operations can be performed using the Boolean operators we reviewed in Lesson 6. The Boolean operations are part of the Java language. To formally implement them, each Number-based class is equipped with a method named compareTo.

 
 
 

Previous Copyright © 2009-2016, FunctionX, Inc. Next