Intern
What is an object in Java?
sobes.tech AI
Answer from AI
Class — is a template or description of how objects will look. Object — is an instance of a class. An object has:
- State: Represented as fields (instance variables) of the object. These are the data stored by the object.
- Behavior: Represented as methods. These are actions that the object can perform or that can be performed on the object.
- Identity: A unique name that distinguishes one object from another. For reference types in Java, the identifier is a reference.
Example:
class Dog {
// State (fields)
String name;
int age;
// Constructor (creating an object)
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
// Behavior (methods)
public void bark() {
System.out.println(name + " barks!");
}
public void growOlder() {
this.age++;
System.out.println(name + " is now " + age + " years old.");
}
public static void main(String[] args) {
// Creating Dog objects
Dog myDog = new Dog("Bobic", 3); // myDog object
Dog hisDog = new Dog("Sharik", 5); // hisDog object
// Accessing object state
System.out.println("My dog's name: " + myDog.name);
System.out.println("His dog's age: " + hisDog.age);
// Calling object behavior
myDog.bark();
hisDog.growOlder();
}
}