Answer to Question #135945 in Java | JSP | JSF for Elizabeth

Question #135945

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.


1
Expert's answer
2020-09-30T16:09:03-0400
/*
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();
  }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS