Java Objects: Academic Resource Center
Java Objects: Academic Resource Center
Object vs Class
A Class is like the idea, or the definition of an actual thing. Car can
be a Class, but "A Car" would be what is called an instance of that
class or, an Object.
To be more specific, we might say that every car has a make and
model, that would be the Class. From there we could make Blue
Corvets, Red Mustangs, and Black Porsche, all Objects.
class Car{
String make;
String model;
}
car1.make = "Red";
car1.model = "Sedan";
}
}
Constructors
We can add our first method to the car class, a constructor, to make
it easier to create Car objects:
this.make = make;
this.model = model;
}
Note that this.make is the Car's make String, and make is the
variable passed in. The same is true for this.model and
model.
class Example{
public static void main(String[] args){
It is quite often the case that you do not want other using your
object to be able to mess with it's variables any way they choose, in
this case you need to make them private. Then what we accessor
and mutator methods can be used to interact with them in specific
ways.
this.make = make;
}
Now we can change the value of make, even though it's
private, because the method setMake, is not private,
and we can access that.
this.make = make;
}
}
Now setMake has a small rule.
return make;
}
Now we can see the value of make, in the same way getMake
worked.
System.out.print(car1.getMake());
car1.setMake("Yellow");
car1.setMake("");
System.out.print(car1.getMake());
}
}
This will print Red, then Yellow.
Implementing toString()
public String toString(){
Reference
Compiled by Corey Sarsfield