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 given code below. Simply convert all properties as variables/ class fields and behaviors/ operations into a method. That’s simple.
Example of creating a class in java
class Person {
// properties
String name;
int age;
// Behaviors
public void eat() {
// write about behaviors
}
public void sleep() {
//// write about behaviors
}
}
Above, we have created a template for person class.
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.
class Car {
String model;
void run() {
//definition
}
}
Now we can create many objects of the Car class like, Maruti and ford etc.
CLASS EXERCISES:
Exercise-1:
Create a class Dog, that has 3 properties (class fields) breed, age and colour with behaviours (class method) bark and sleep.
Exercise-2:
There is a car, which has attributes model and price, and the car has functionalities start, stop and move. Also, there is a driver, having attributes name and age, and the behaviour drive.
Model the classes Car and Driver. You need to take care of the accessibility of the attributes from outside the class for the best design.
Create a class Dog, that has 3 properties (class fields) breed, age and colour with behaviours (class method) bark and sleep.