What is Class?
Class is a blueprint or a template that allows us to define the properties (attributes or fields) and behaviors (methods or functions) that the objects will have.
Note:- In simpler terms, a class is a user-defined data type that encapsulates data and the operations that can be performed on that data.
1. Attributes (Fields): These are variables that represent the characteristics or properties of an object. Fields define the state of an object.
Example
public class Dog {
// Fields
String name;
int age;
String breed;
}
Note:- In this example, the Dog class has fields such as name, age, and breed.
2. Methods (Member Functions): These are functions that define the behavior of an object. Methods perform actions or operations related to the object's state.
Example
public class Dog {
// Method
public void bark() {
System.out.println("Woof! Woof!");
}
}
Note:- The Dog class has a method named bark that represents the action of a dog barking.
What is Object?
An object is an instance of a class, as we know class serves as a blueprint or template for creating objects, meanwhile an object is a concrete instantiation of that blueprint.
Example
public class Dog {
// Fields
String name;
int age;
String breed;
// Method
public void bark() {
System.out.println("Woof! Woof!");
}
}
public class Main{
public static void main(String[] args){
// Creating an object and invoking a method
Dog myDog = new Dog();
myDog.bark(); // Invoking the bark method of the Dog class
}
}
Note :- we can multiple objects for a single class, it's depend on requirements.