In part two of this ten part series, I discussed some basic Java language syntax. In this article, I will discuss some of the Java primitive types and describe the basics of a Java class. I will also touch on the JDK (Java Development Kit) and describe how to compile a small class.
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