Syntax and Declaration
Basic Syntax Structure
The syntax for declaring a public class in Java follows a specific pattern:
graph LR
A[Access Modifier] --> B[class]
B --> C[Class Name]
C --> D[{ Class Body }]
Detailed Declaration Syntax
public class ClassName {
// Class members
// Constructors
// Methods
}
Declaration Rules and Components
Component |
Description |
Requirements |
Access Modifier |
Defines class visibility |
Must be public |
Class Keyword |
Indicates class definition |
Always class |
Class Name |
Identifier for the class |
Must start with uppercase |
Class Body |
Contains class members |
Enclosed in curly braces |
Complete Example in Ubuntu
Let's demonstrate a comprehensive public class declaration:
## Create Java file in Ubuntu
nano PersonClass.java
public class PersonClass {
// Instance variables
private String name;
private int age;
// Constructor
public PersonClass(String name, int age) {
this.name = name;
this.age = age;
}
// Public method
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
// Main method for execution
public static void main(String[] args) {
PersonClass person = new PersonClass("LabEx Student", 25);
person.displayInfo();
}
}
Advanced Declaration Patterns
Nested Public Classes
public class OuterClass {
public class InnerPublicClass {
// Nested public class implementation
}
}
Abstract Public Classes
public abstract class AbstractPersonClass {
// Abstract method
public abstract void performAction();
}
Compilation and Execution
## Compile the Java file
javac PersonClass.java
## Run the compiled class
java PersonClass
Best Practices
- Use meaningful and descriptive class names
- Follow CamelCase naming convention
- Keep classes focused and modular
- Use appropriate access modifiers
- Document class purpose and functionality
By mastering these syntax and declaration techniques, you'll write more structured and professional Java code in your LabEx programming journey.