| | |
    Java Beginner Home
    Table of Contents
    Introduction to Java
    Getting Started with Java
    Basic Language Elements
    Java Operators
    Java Control Statements
    Java Access Modifiers
    Classes and Objects
    Java Constructors
    Object Serialization
    Java Class Inheritance
    Java Object Type Casting
    Abstract class and Interface
    Java Method Overiding
    Java toString Method
    Java String Class
    Java String Comparison
    Java StringBuffer
    Java Exceptions
    Singleton Pattern
    Java Threads Tutorial
    Java Collections Framework
    Java Date Util
    Swing Tutorial
    Download Java Software
    Advertise
    Feedback
    Java books
    Eclipse Plugin Site

Java Classes and Objects



Introduction to Java Classes

A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.

Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.

A class has the following general syntax:

<class modifiers>class<class name>
<extends clause> <implements clause>
{

// Dealing with Classes (Class body)
<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}

Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().

public class Cube {

	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
}

How do you reference a data member/function?

This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.
( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).

For example:

cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()

Class Variables – Static Fields

We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method.

Instance Variables

Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.

Consider this simple Java program showing the use of static fields and static methods

// Class and Object initialization showing the Object Oriented concepts in Java
class Cube {

	int length = 10;
	int breadth = 10;
	int height = 10;
	public static int numOfCubes = 0; // static variable
	public static int getNoOfCubes() { //static method
		return numOfCubes;
	}
	public Cube() {
		numOfCubes++; //
	}
}

public class CubeStaticTest {

	public static void main(String args[]) {
		System.out.println("Number of Cube objects = " + Cube.numOfCubes);
		System.out.println("Number of Cube objects = "
				+ Cube.getNoOfCubes());
	}
}

Download CubeStaticTest.java

Output

Number of Cube objects = 0
Number of Cube objects = 0

Final Variable, Methods and Classes

In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.

Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.


Introduction to Java Objects

The Object Class is the super class for all classes in Java.

Some of the object class methods are

equals
toString()
wait()
notify()
notifyAll()
hashcode()
clone()

An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.

An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.

Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.

When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.

Below is an example showing the creation of Cube objects by using the new operator.

public class Cube {

	int length = 10;
	int breadth = 10;
	int height = 10;
	public int getVolume() {
		return (length * breadth * height);
	}
	public static void main(String[] args) {
		Cube cubeObj; // Creates a Cube Reference
		cubeObj = new Cube(); // Creates an Object of Cube
		System.out.println("Volume of Cube is : " + cubeObj.getVolume());
	}
}

Download Cube.java

Method Overloading

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call

Below is an example of a class demonstrating Method Overloading


public class MethodOverloadDemo {

	void sumOfParams() { // First Version
		System.out.println("No parameters");
	}
	void sumOfParams(int a) { // Second Version
		System.out.println("One parameter: " + a);
	}
	int sumOfParams(int a, int b) { // Third Version
		System.out.println("Two parameters: " + a + " , " + b);
		return a + b;
	}
	double sumOfParams(double a, double b) { // Fourth Version
		System.out.println("Two double parameters: " + a + " , " + b);
		return a + b;
	}
	public static void main(String args[]) {
		MethodOverloadDemo moDemo = new MethodOverloadDemo();
		int intResult;
		double doubleResult;
		moDemo.sumOfParams();
		System.out.println();
		moDemo.sumOfParams(2);
		System.out.println();
		intResult = moDemo.sumOfParams(10, 20);
		System.out.println("Sum is  " + intResult);
		System.out.println();
		doubleResult = moDemo.sumOfParams(1.1, 2.2);
		System.out.println("Sum is  " + doubleResult);
		System.out.println();
	}
}

Download MethodOverloadDemo.java

Output

No parameters

One parameter: 2

Two parameters: 10 , 20
Sum is 30

Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003

Below is a code snippet to shows the interfaces that a Class Implements:

Class cls = java.lang.String.class;
Class[] intfs = cls.getInterfaces();
// [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable]
// The interfaces for a primitive type is an empty array
cls = int.class;
intfs = cls.getInterfaces(); // []

Below is a code snippet to show whether a Class Object Represents a Class or Interface:

Class cls = java.lang.String.class;
boolean isClass = !cls.isInterface(); // true
cls = java.lang.Cloneable.class;
isClass = !cls.isInterface(); // false

 
 
    Java is a trademark of Sun Microsystems, Inc.
| | |
© Copyright 2007-08 javabeginner.com