The class is the logical construct upon which the entire Java language is built because it defines the shape and nature of the object. Any concept you wish to implement in a Java program must be encapsulated within a class.
Perhaps the most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus the class is a template for an object, and an object is an instance of a class.
On a high level, a Class consists of Variables and Methods. Variables store data and Methods will contian the code to use the data.
'class' syntax |
class classname { type instance-variable1; type instance-variable2; - - type instance-variableN; type methodname1(parameter-list) { //body of the method } type methodname2(parameter-list) { //body of the method } - - type methodnameN(parameter-list) { //body of the method } } |
Instance Variables - The data or variables defined in the class are called Instance variables Example int i; (Here we've defined the instance variable 'i' as int) Methods - The code is contained inside the methods. Example public static void main(String args[]) { i=0; if(i==1) System.out.println("The value of i is 1"); else System.out.println("The value of i is "+i); } i.e. The statements inside the method 'main( )' is nothing but code |
Collectively, the variables and methods defined within a class are called members of the class. |
Simple example to demonstrate the 'class' |
class Box { double width; double height; double depth; public static void main(String args[]) { double volume; volume = width*height*depth; System.out.println("The volume of the Box is "+volume); } } |