How to define a class in Java
Overview
A Java class is the template from which objects are created. It is a blueprint for an object. A class is created using the keyword class.
Classes can contain methods, which are actions that the class can perform, and fields, which are variables that contain data used by the class. When we create a new object, we create an instance of a class.
Syntax
To declare a class in Java, use the following format:
class ClassName {// class body}
The name of the class should be followed by the keyword class. The body of the class is enclosed within curly braces {}.All the data members and member functions of the class are declared inside the body of the class.
Code example
Let's look at the example of the Java class below:
public class Person {// fieldsString name;// methodsvoid printName() {System.out.println(name);}}
This Java class has the name Person.The keyword public is an access modifier, which determines who can access this class. In this case, the class is accessible by any other class. Inside the body of the class, we can declare fields and methods.
Fields
Fields are variables that contain data. In the example above, we have a field named name.Fields are usually declared at the top of the class before any methods.
Methods
Methods are functions that perform actions. In the example above, we have a method named printName(), which prints the value of the name field to the screen.Methods are usually declared after the fields in a class.
To use a class, we need to create an instance of the class. To do this, we use the keyword new. For example, if we want to create an instance of the Person class, we would use the following code:
Person myObj = new Person();
This creates an object called myObj, which is an instance of the Person class We can then access the fields and methods of this object using the dot notation, like this:
myObj.name = "John Doe";myObj.printName();
This set the name field to "John Doe" and then call the printName() method, which print the value of the name field to the screen.
class Person {// fieldsString name;// methodsvoid printName() {System.out.println(name);}}class Main {public static void main( String args[] ) {Person myObj = new Person();myObj.name = "John Doe";myObj.printName();}}
Code explanation
- In the code above, we create a class named
Personthat has a field name and a methodprintName(). - In the
main()method, we create an object of the class and assign a value to the name field. - Finally, we invoke the
printName()method on the object to print the value of the name.
Conclusion
A class is like a blueprint, while an object is like a machine built for the blueprint. In this answer, we learned about classes and objects in Java and how to use them with the help of an example.