Java: ClassWhat Is a Class? Just like we do in science, we classify objects in Java. All objects that are 'of the same sort' are in a 'class of object'. But in the real world we are classifying objects that have already been made (by a God, in you believe in divine orchestration of the Universe - or by evolution if you believe that there is no God). To understand computing it is easier if you believe in there being a creator God - as you as programmer take on his role in the cyber-world. If, as cyber-god, you are going to make a lot of similar objects, the best way to do it is to create a 'class'. When you write a class - you are 'creating' a blueprint from which you can create individual objects or instances that exist in cyberspace. You therefore have to decide upon the characteristics those objects will have in common and include them in your 'class'. When you them go on to make instances (individual objects) you will be able to create them with 'cyber-god-given' characteristics (called states) to start with. For example (taken from the Java site) In the real world, there may be thousands of bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components... they may differ in colour, but they are all classed as being the same model of a particular make. Lets make a cyber-bicycle. The first thing you (as cyber-creator) have to do is make the 'blueprint' for all bicycles that will be created in cyberspace. You have to write the 'class'.
The Bicycle class does not contain a main method. That is because it's not a complete application; it's just the blueprint for some characteristics of bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your Java program - or 'application' as it is known. Here's a BicycleDemo class that creates two separate Bicycle objects by using the Bicycle class and invoking the methods within that class:
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles: cadence:50 speed:10 gear:2
|
|