Give an example of a class and an example of an object. Describe what a class is, what an object is, and how they are related. Use your examples to illustrate the descriptions.
/*
Class is a template that describes state and behavior of the object.
Object is a representation (or instance) of the class.
In example below, Appliance class is used to create two objects.
Every object has own state - name, and common behavior - turnOn/turnOff.
*/
class Appliance {
String name;
public Appliance(String name) {
this.name = name;
}
public void turnOn() {
System.out.println(this.name + " is tuned on!");
}
public void turnOff() {
System.out.println(this.name + " is tuned off!");
}
}
class Main {
public static void main(String[] args) {
// Create fridge object
Appliance fridge = new Appliance("Fridge");
fridge.turnOn();
// Create microwave object
Appliance microwave = new Appliance("Microwave");
microwave.turnOn();
}
}
Comments
Leave a comment