A class the basic building block of an object-oriented language such as Java is a template that describes the data and behavior associated with instances of that class. The data associated with a class or object is stored in variables; the behavior associated with a class or object is implemented with methods.
A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can ( and usually do) get much more complex.
The general form of a class definition is shown here:
class classname
{
type instance-variable1;
type instance-variable2;
// ..
type instance-variableN;
type methodname1(parameter-list)
{
//body of method
}
type methodname2(parameter-list) {
//body of method
}
//..
type methodnameN(parameter-list) {
// body of method
}
}
A SIMPLE CLASS
Let's begin our study of the class with a simple example.Here is aa class called Box that defines three instance variables:width,height and depth.
class Box
{
double width;
double height;
double depth;
}
class Box
{
double width;
double height;
double depth;
}
Example of class
/* A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main9String args[])
{
Box myBox=new Box;
double vol;
//assign values to mybox's instance variables
mybox.width=10;
mybox.height=20;
mybox.depth=15;
//compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is" +vol);
}
}
To run this program,you must execute BoxDemo.class.When you do,you will see the following output:
Volume is 3000.0
Example of class
/* A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main9String args[])
{
Box myBox=new Box;
double vol;
//assign values to mybox's instance variables
mybox.width=10;
mybox.height=20;
mybox.depth=15;
//compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is" +vol);
}
}
To run this program,you must execute BoxDemo.class.When you do,you will see the following output:
Volume is 3000.0
No comments :
Post a Comment