How to Create Class in Java: Syntax and Example
In Java, you create a class using the
class keyword followed by the class name and curly braces. Inside the class, you can define variables and methods to describe the object's properties and behaviors.Syntax
A Java class is defined using the class keyword, followed by the class name and a pair of curly braces { }. Inside the braces, you can add variables (to store data) and methods (to perform actions).
- class: keyword to declare a class
- ClassName: the name of your class (should start with a capital letter)
- { }: curly braces to hold the class body
java
class ClassName { // variables and methods go here }
Example
This example shows how to create a simple class named Car with a variable and a method. The main method creates an object of the class and calls its method.
java
class Car { String color; // variable to store color void displayColor() { System.out.println("Car color is " + color); } public static void main(String[] args) { Car myCar = new Car(); // create object myCar.color = "red"; // set variable myCar.displayColor(); // call method } }
Output
Car color is red
Common Pitfalls
Common mistakes when creating classes in Java include:
- Forgetting to use the
classkeyword. - Not capitalizing the class name (Java convention).
- Missing curly braces
{ }around the class body. - Trying to call methods or access variables without creating an object (unless the method is
static).
Here is an example of a wrong and right way:
java
// Wrong: missing class keyword and braces // Car { // String color; // } // Right: class Car { String color; }
Quick Reference
Remember these key points when creating a class in Java:
- Use
class ClassName { }to define a class. - Class names start with a capital letter.
- Variables hold data; methods define actions.
- Create objects with
new ClassName()to use non-static members.
Key Takeaways
Use the
class keyword followed by a capitalized name and curly braces to create a class.Inside the class, define variables and methods to describe data and behavior.
Create objects with
new ClassName() to access non-static members.Always include curly braces to enclose the class body.
Follow Java naming conventions for readability and best practice.