Class Fundamentals
A class is a template that defines the form of an object. It specifies both the data and the code that will operate on that data. Java uses a class specification to construct objects. Objects are instances of a class. Thus, a class is essentially a set of plans that specify how to build an object. It is important to be clear on one issue: a class is a logical abstraction. It is not until an object of that class has been created that a physical representation of that class exists in memory
The General Form of a Class
Since a class is collection of data members and member functions. Java has a plain syntax of creating class. General form of a syntax is :
class ClassName { access-specifier type1 variable1; access-specifier type2 variable2; . . access-specifier typeN variableN; type method(parameters) { } type method(parameters) { } . .. typeN methodN(parameters) { } } // ending brace
Defining a Class
Let’s create a class for a car as:
class Car { // data members int gear; int speed; int RPM; Car() // constructor Car called when car starts { RPM = 1000; // some engine RPM when car starts } // Member functions void setGear(int newValue) { // set the gear to some value gear = newValue; } void applyBrake(int decrement) { // break applying will decrease speed speed -= decrement; } void speedUp(int increment) { // pushing accelerator will speed up car speed += increment; } }