char Keyword in Java
The class
keyword in Java is fundamental to the language's object-oriented programming model. It is used to define a new class, which can contain fields (variables) and methods to define the behavior of objects created from the class.
Usage
A class serves as a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data.
Syntax
class ClassName {
// fields
// methods
}
ClassName
: The name of the class, which should start with an uppercase letter by convention.fields
: Variables that hold the state of the class.methods
: Functions that define the behavior of the class.
Examples
Example 1: Basic Class Definition
class Animal {
String name;
int age;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Animal();
dog.name = "Buddy";
dog.age = 5;
dog.displayInfo();
}
}
In this example, the Animal
class has two fields, name
and age
, and one method, displayInfo()
. The Main
class demonstrates creating an Animal
object and setting its fields.
Example 2: Class with Constructor
class Car {
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
void displayDetails() {
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", 2020);
car.displayDetails();
}
}
This example introduces a constructor in the Car
class to initialize the model
and year
fields. The Main
class creates a Car
object using the constructor and displays its details.
Example 3: Inheritance
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
}
}
This example demonstrates inheritance. The Dog
class extends the Animal
class and overrides the makeSound()
method. The Main
class creates a Dog
object and calls the overridden method.
Tips and Best Practices
- Naming Conventions: Always start class names with an uppercase letter and use camel case for readability.
- Encapsulation: Use private fields and provide public getter and setter methods to protect the internal state of the class.
class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
- Single Responsibility Principle: Each class should have a single responsibility or purpose. This makes the class easier to understand and maintain.
- Constructor Initialization: Use constructors to initialize fields and ensure that objects are created in a valid state.
- Inheritance and Polymorphism: Leverage inheritance to create a natural hierarchy and polymorphism to achieve dynamic method dispatch.