Previous | Home | Next |
In object-oriented programming languages like Java, a class is a construct that is used as a template to create objects of that class. This construct describes the state and behaviour that the objects of the class share.
Since in Java we cannot do anything without class, so when we write a source code in java we are actually creating a class but not object. Writing a class is called implementing a class and has two main components :the class declaration and the class body. Class declaration contains name of the class and other attributes like access modifiers, whereas class body consists of various methods, variables, and the logic of the code. The body of a class is contained within the curly{}braces, can be declared as :
access-modifier class ClassName { //some variables // methods // logic of code }
Objects in java are the entities in the real world problem, and are the building blocks of any Java program. Whenever we write a source code, we are writting a class and code for creating the objects from that class. Thus, when a program is running objects are created for doing their specific jobs for which they have been created.
Thus, we can say that a class is a template that we write and objects are created from the class. In technical terms we can say that an object is instantiated from a class and this process is called instantiation, that's why objects are also called the instances of the class.
Every class in Java have the following components :
- fields: Fields are variables that held data specific to each object. For e.g., a student may have an ID number, also known as member variables.
- methods: Methods perform operations on an object. For e.g., a student may have to see his/her marks.
- static fields: Static fields are common to any object of the same class, only one static field exists for one class.
- static methods :Static methods are methods that do not affect a specific object.
- nested classes: It is useful to contain a class within another one if it cannot be accessed outside of the class.
- Java Tutorialsconstructors: It is a special method that generates a new object and have same name as of a class.
Java Tutorialsclass ShowClass { private static int i=0; //defined a static field int j=1; ShowClass() { //default constructor declaration } public static void show() //defined a static method { System.out.println("The value of i is :"+i); //System.out.println("The value of j is :"+j); //this statement will cause compilation error, since j is non-static } public static void main(String args[]) { ShowClass sc=new ShowClass(); show(); //we don't have to create an object to call a static method sc.show(); } }
Previous | Home | Next |