Class in Java – Learn What Is Class and How to Write It

(Last Updated On: March 2, 2019)

Class in Java – Learn what is class and how to write a class in java with simple example and explanation.

A class is a template that contains properties(variables) and behaviors(methods) in java . We can create many objects of it.

Sounds difficult? Read till end and you understand class in java for sure! It’s Simple!!!

For example, a person has some properties and behaviors. As a property, a person has his name, age, gender etc. and behavior as eat and sleep etc.

So, we can convert a person class as below in java. Simply convert all properties as variables/ class fields and behaviors/ operations into a method. That’s simple.

Example of creating a class in java

A template for person class we have created. Now, we can create many objects of the person class. Objects can be any person i.e. Peter, John and Linda etc. Everyone has his properties and behaviors i.e. name and age etc and behaviors eat and sleep etc.

Similarly, everything you see around you are objects like Car, book, pen and computer etc. for that you can create a template /blue print and create objects of them.

See one more example, a Car his properties like model and brand etc and behavior run. So, we can convert into a class as below. Convert model into a property and behavior int a method.

 

Now we can create many objects of the class Car like, Maruti and ford etc.

 

Exercise:

Create a class Dog, that has 3 properties (class fields) breed, age and colour with behaviours (class method) bark and sleep.

Solution: