Programming & Scripting Tutorials

Java: Classes and Member Functions



Classes in java mean you don't have to reuse the same code over and over, and you can create object and change attributes and things using generalised function code (in classes).

It's quite hard to explain, I suggest you should read through this example, where we have robots which we can create:

class Robot{
Robot(double inputPower, double inputSpeed, double inputBattery){
Power = inputPower;
Speed = inputSpeed;
Battery = inputBattery;
}
void DisplayProperties(){
    System.out.println("Power: " + Power);
    System.out.println("Speed: " + Speed);
    System.out.println("Battery:" + Battery);
    System.out.println("Rating :" + (Power + Speed + Battery));
}
void TurnOn(){
    On = true;
}
void TurnOff(){
    On = false;
}

double Speed;
double Power;
double Battery;
boolean On = false;
}

public class Main {
     public static void main(String[] args) {

         Robot Robot1 = new Robot(10, 52, 100);
        if(Robot1.On == true){
            Robot1.DisplayProperties();
        } else if (Robot1.On == false){
         System.out.println("Robot1 is not on...");
        }
         Robot1.TurnOn();
         if(Robot1.On == true){
            Robot1.DisplayProperties();
        } else if (Robot1.On == false){
         System.out.println("Robot1 is not on...");
        }
     
  }
}

Lets take a closer look at some of the lines you might not understand.

void DisplayProperties(){
}

This is a simple member function, its a void as it doesn't return a value, anything inside does what its meant to when its called.

class Robot{


This simply creates the class "Robot"

Robot Robot1 = new Robot(10, 52, 100);


Lets break this bit up a bit..

Robot Robot1


The above tells the program that "Robot1" is going to be a robot object, and it tells the program that "Robot1" will be a Robot object.

= new Robot(10, 52, 100);


This simply creates a new instance of the robot class, and then calls the constructor and fills in the specified parameters.


Robot(double inputPower, double inputSpeed, double inputBattery){


You may have noticed that this is the same but different from the other member function. That's because this is the constructor, you know its the constructor as instead of "void name(PARAMETERS){" it says "classname(PARAMETERS){".

Putting parameters into any class or function simply means that when the function (or constructor) is called it wants an input of the values specified (usually because it wants to do things with them).


You can also create new classes (public ones this time (there pretty much the same)) by creating new java files, in netbeans you do this by clicking the new file button, and then Java class (they are accessed and dealt with in exactly the same way).


This Java tutorial was written by


Back to Java

Advertisement: