Java Part 3: Primitive Types - Creating our first class
(Page 3 of 6 )
We will write a trivial class, which will hold no real purpose, other than to show us the basics of classes and objects. Our class will be called “Number”. The code for our class is shown below. To keep it simple, I have left out some features that an entirely correct class would contain. The most prominent of these omissions are the visibility declarations, which I will be discussing in furture articles.
class Number { // The class definition
float value = 0; // A Class member, float type,
// set to zere by defualt.
Number(){} // The default constructor
Number( float val ){ // Another Constructor.
value = val;
}
public static void main( String[] args ){
Number number = new Number();
number.addTo( 5 );
number.divideBy( 5 );
System.out.println( +number.getVal() );
System.exit(1);
}
float addTo( float x ) { // The Following 4 methods manipulate
return value += x; // the class member "value"
}
float subFrom( float x ) {
return value -= x;
}
float multiplyBy( float x ) {
return value *= x;
}
float divideBy( float x ) {
if( value == 0 ){
return 0;
}
return value /= x;
}
float getVal() { // An accessor method, that simply returns
return value; // the value of the "value" member
}
} Next: Our new class...explained >>
More Java Articles
More By Chris Noack