A class is any group of objects that belong together.
These objects contain shared properties or attributes, or they may also share common behavior or function.
For instance, we may define the objects Pig, Chicken, and Horse as part of a class Animal.
graph TD pig("Pig") chick("Chicken") horse("Horse") subgraph Animal pig chick horse end
Defining a Class
In Java, to define a class, we use the class keyword, followed by the name of the class.
class Animal {
int weight = 10;
}Creating an Object from a Class
Now that we have a class Animal, we can make some objects of that class.
To create an object, we simply have to follow the following syntax:
ClassName objName = new ClassName();So to create a Pig object from the Animal class, we do this:
public class Main {
public static void main(String[] args) {
Animal pig = new Animal();
}
}We can create multiple objects from the same class in the same way.
For example, we can create an another object horse from the class Animal.
public class Main {
public static void main(String[] args) {
Animal pig = new Animal();
Animal horse = new Animal();
}
}Classes and objects are much powerful when we utilize its key features, such as class attributes and class methods.
We will begin working with classes in the next section.