Pages

Sunday, June 10, 2012

Classes


Here we are going to explain the definition of a class. A class is an object that could be used in a main programm. This class has usually properties and methods. The properties can be modified by the user with the gets and sets methods. And the methods are used to get some results related to the class. This can be better explained with an example:
public class ObjectA {
//private properties
int property1;
int property2;
//constructor
public ObjectA(){
this.property1 = 0;
this.property2 = 0;
}
//gets and sets methods
public int getProperty1(){
return this.property1;
}
public void setProperty1(int property1){
this.property1 = property1;
}
public int getProperty2(){
return this.property2;
}
public void setProperty2(int property2){
this.property2 = property2;
}
//another method
public void increment(){
this.property1++;
this.property2++;
}
}

Now I am going to explain the example. First there is a class called ObjectA, which has to properties (property1 and property2). The properties can be accessed and modified by the get and set methods. Thus there is anohter method "increment" which increment the value of the variables property1 and property2 in one value. And finally, there is the constructor. The constructor is needed to create a local copy of the class ObjectA. In the constructor we can initialize the variables and call private methods if it is necessary.

There are multiple types of classes: enum, abstract, interface or class. All must be public if they are alone in the file. If anyone is inside another, it can be public or private. The main class of the file must be named as the file.

No comments:

Post a Comment