Declaring a Class: Syntax and Naming Conventions
You'll learn the exact syntax for declaring a Java class and the naming rules you must follow.
The Basic Syntax
Now that you understand a class is a blueprint for objects, let's see how to actually write one. The simplest class declaration looks like this:
public class MyClass {
// class body goes here
}
Let's break down each part:
public– an access modifier (controls who can see this class)class– the keyword that tells Java you're declaring a classMyClass– the name you choose for your class{ }– curly braces that contain the class body (where you'll eventually add variables and methods)
Naming Rules and Conventions
Java has strict rules and style conventions for class names:
Required Rules (enforced by the compiler):
- Must start with a letter, underscore
_, or dollar sign$ - Cannot start with a digit
- Cannot be a Java keyword (
class,public,int, etc.) - Can contain letters, digits, underscores, and dollar signs
Java Conventions (not enforced, but strongly recommended):
- Use PascalCase: capitalize the first letter of each word (
BankAccount,User,ShoppingCart) - Use nouns: classes represent things (
Car,Student,Invoice) - Avoid underscores and dollar signs (legal, but against convention)
- Make names descriptive:
Personis better thanP
// Good examples
public class Customer { }
public class SavingsAccount { }
public class EmailValidator { }
// Legal but poor style
public class customer { } // should be capitalized
public class CUST { } // unclear abbreviation
Key Takeaway: A class declaration starts with public class ClassName { }, where ClassName follows PascalCase naming conventions—capitalize each word and use descriptive nouns.