Anda di halaman 1dari 2

A class acts as a blueprint, what I mean by this is, a class describes how you are going to build

a program. When you write a class it has a general outline to describe something that can then be
called later and given more specific details. A class is made up of attributes and methods.
The attributes describe the characteristics of the class and the methods describe what the class
can do. For example if I wanted to I could create the class car.
public class Car {
So this is the class I want to create; now I can add the attributes of the class Car.
public class Car {
int wheels = 4;
int doors;
int mirrors ;
int topspeed;
These are the attributes of the class Car. All vehicles that are classified in the class Car will have
4 wheels, the other attributes doors, mirrors, and the top speed will vary depending on the car we
are describing. Now that we have our attributes we can add our methods.
public void doorCount(int num){
doors = num;
}
public void mirrorCount(int num){
mirrors = num;
}
public void fastOrslow(int speed){
topspeed = speed;
}
public void carStats(){
System.out.println("Your car has " + doors + " doors and " + mirrors + " mirrors and goes
"+ topspeed + " mph");
if (topspeed <= 120){
System.out.println("your car is slow.");
} else{
System.out.println("your car is fast."); }
These are the methods of the class Car. These methods personalize the cars attributes (the
number of doors, mirrors and the top speed of the car). The last method carStats does a print out
of the number of doors and mirrors your car has, and describes if your car is fast or slow
depending on the top speed. Now that we have our Class, attributes, and methods, let use create
our object otherwise known as instantiate a new class.
public static void main(String[] args) {
Car Mustang = new Car();
The Variable Mustang refers to the newly created object. Creating a new object is the same as
instantiation of a new class. We can now take the newly created object and apply the methods to
it.
public static void main(String[] args) {

Car Mustang = new Car();

Mustang.fastOrslow(180);
Mustang.doorCount(2);
Mustang.mirrorCount(6);
Mustang.carStats();
}
}
Ive taken the object Mustang and given actual parameters to all the formal parameters of each
method and the final method (carStats) which prints out the stats for the car mustang. The oput
for this example would be.
Your car has 2 doors, 6 mirrors and goes 180 mph
your car is fast.

Anda mungkin juga menyukai