What is a class?

BerkayHasip
3 min readJan 28, 2024

--

A class is a template or a blueprint for creating objects in Java. An object is a collection of data and methods that can perform some actions. For example, you can create a class called Dog that has data such as name, breed, and age, and methods such as bark, eat, and sleep.

Photo by Web

How to create a class?

To create a class in Java, you need to use the keyword class followed by the name of the class. The name of the class should start with a capital letter and follow the camel case convention. For example, Dog, Student, and Car are valid class names. The class name should also be descriptive and meaningful.

The body of the class is enclosed in curly braces { }. Inside the class body, you can declare the data and methods of the class. The data are also called fields or attributes, and the methods are also called functions or behaviors. For example, this is how you can create a class called Dog:

Java

class Dog {
// declare the fields of the class
String name;
String breed;
int age;
  // declare the methods of the class
void bark() {
// code to make the dog bark
}
void eat() {
// code to make the dog eat
}
void sleep() {
// code to make the dog sleep
}
}

How to use a class?

To use a class, you need to create an instance or an object of the class. To create an object, you need to use the keyword new followed by the name of the class and parentheses (). For example, this is how you can create an object of the class Dog:

Java

Dog myDog = new Dog();

This statement creates a new object of the class Dog and assigns it to the variable myDog. The variable myDog is also called a reference to the object, because it points to the memory location where the object is stored.

To access the fields and methods of the object, you need to use the dot operator . followed by the name of the field or method. For example, this is how you can access the fields and methods of the object myDog:

Java

// access the fields of the object
myDog.name = "Rex";
myDog.breed = "German Shepherd";
myDog.age = 3;
// access the methods of the object
myDog.bark();
myDog.eat();
myDog.sleep();

This code assigns some values to the fields of the object myDog and calls the methods of the object myDog.

Summary

In this article, you learned about classes in Java. A class is a template for creating objects, which are collections of data and methods. To create a class, you need to use the keyword class followed by the name of the class. To create an object, you need to use the keyword new followed by the name of the class and parentheses. To access the fields and methods of the object, you need to use the dot operator followed by the name of the field or method.

--

--

BerkayHasip

Website : berkayhasip.com / Hi! Student , Java lover. Self-taught, blog my journey. Create apps, freelance, advise, and blog. Eager for diverse projects