Tutorial search
Cool Stuff
How would you like to MASTER graphic design by next week?
Click here to find out how
Photoshop Templates
Java Tutorials
Tutorials
Stuff
Affiliates
Creating classes in Java - Java tutorial
In java everything should be defined as Class
{
// Declaration of Data Members
// Declaration of methods.
}
Classes contain methods to perform the function assigned to the class.
Creating Objects of Classes
An object is an instance of the class and has a unique identity. The identity of the object distinguishes it from other objects. Classes and objects are closely linked to each other. To create an object, you need to perform the following steps:
- Declaration:
Declares a variable that holds the reference to the object.classname objectname; - Instantiation or Creation
- Creates an object of the specified class. When you declare an object, memory is not allocated to it.
- To allocate memory to the object, you need to use the new operator.
The new operator allocates memory to an object and returns a reference to that memory location in that object variable.Objectname = new classname ();
Adding Methods to Classes
Methods are used to perform certain functions inside the class.
The syntax to add a method to a class
{
//method body
}
Declaring the main () method:
A java program consists of the main () method that calls the methods defined in a class. You can create a number of classes in a java program. The compiler complies all the classes in an application but to execute a program, you need to include a main () method in the program.
Syntax to declare main () method:
{
// code for the main() method
}
In the above syntax, the main () method contains 3 keywords, they are:
- Public: This keyword indicates that the method can be accessed from any object in a java program.
- Static: This keyword indicates that, you need not create an object of the class to call the main () method.
- Void: The void keyword signifies that the main () method returns no value.
Defining Constructors
A constructor of the classes automatically initializes the data members of the class when you create an object.
{
}
Constructors have the following characteristics:
- A constructor is a method with same of the class name.
- A constructor is automatically invoked every time an instance of a class is created.
- Constructors do not have a return type.
Accessing Data Members of a Class
You need to assign values to data members of the object before using them. You can access the data members of a class outside the class by specifying the object name followed by the operator and the data member name.
e.g.;-
b1.studentid=7;
b1 - object name.
studentid – data member.
Setting the CLASSPATH
CLASSPATH is the environment variable, which shows the java compiler, javac.exe, the location where the class files are stored.
The syntax to set classpath
In the preceding syntax, semi-colons separate the multiple entries in classpath.


