You are here:   HomeJava ProgrammingIntroduction to Javajava Classes
by Dinesh Thakur Category: Introduction to Java

In the real world, you'll often find many individual objects all of the same kind.All the objects that have similar properties and similar behavior are grouped together to form a class.

In other words we can say that a class is a user defined data type and objects are the instance variables of class. There may be thousands of other bicycles in existence, all of the same make andmodel. Each bicycle was built from the same set of blueprints and thereforecontains the same components. In object-oriented terms, we say that your bicycleis an instance of the class of objects known as bicycles. A class is the blueprint fromwhich individual objects are created.

 

The following Bicycle class is one possible implementation of a bicycle :

 

class Bicycle {

int cadence = 0;

int speed = 0;

int gear = 1;

void changeCadence(int newValue) {

cadence = newValue;

}

void changeGear(int newValue) {

gear = newValue;

}

void printStates() {

System.out.println("cadence:"+cadence+"speed:"+speed+" gear:"+gear);

}

}

 

The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application.

Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods :

 

class BicycleDemo {

 

public static void main(String[] args) {

// Create two different Bicycle objects

Bicycle bike1 = new Bicycle();

Bicycle bike2 = new Bicycle();

// Invoke methods on those objects

bike1.changeCadence(50);

bike1.changeGear(2);

bike1.printStates();

bike2.changeCadence(50);

bike2.changeGear(2);

bike2.changeCadence(40);

bike2.changeGear(3);

bike2.printStates();

}

}

 

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles :

 

Cadence : 50 speed : 10 gear : 2

Cadence : 40 speed : 20 gear : 3





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular