Search⌘ K

Declaration and Implementation

Explore how to declare and implement classes in Java, including defining attributes and methods. Learn to create objects using the new keyword, enabling you to write modular code through hands-on examples such as implementing a Car class.

The written code of a class and its attributes are known as the definition or implementation of the class.

Declaration

In Java, we define classes in the following way:

Java
class ClassName { // Class name
/* All member variables
and methods*/
}

The class keyword tells the compiler that we are creating our custom class. All the members of the class will be defined within the class scope.

Creating a class object

The name of the class, ClassName, will be used to create an instance of the class in our main program. We can create an object of a class by using the keyword new:

Java
class ClassName { // Class name
...
// Main method
public static void main(String args[]) {
ClassName obj = new ClassName(); // className object
}
}

Implementation of a Car class

Let’s implement the Car class illustrated below:

Java
//The Structure of a Java Class
class Car { // Class name
// Class Data members
int topSpeed;
int totalSeats;
int fuelCapacity;
String manufacturer;
// Class Methods
void refuel(){
...
}
void park(){
...
}
void drive(){
...
}
}