Java classes
In Java, a class is a blueprint or a template for creating objects. It defines the attributes (fields) and behaviors (methods) that the objects created from the class will have. A class is a fundamental building block in Java, supporting object-oriented programming (OOP) principles like encapsulation, inheritance, and polymorphism.
Key Components of a Java Class:
Fields (Attributes or Variables): These are the properties or data members of the class. They define the state or characteristics of the objects.
Methods: These define the behaviors or actions that an object of the class can perform. Methods contain the logic or functionality of the class.
Constructors: Special methods used to initialize objects. They are invoked when a new object is created.
Access Modifiers: These control the visibility and access of the class, its fields, methods, and constructors (e.g.,
public
,private
,protected
).Objects: Objects are instances of a class. An object represents a real-world entity and has states and behaviors defined by its class.
Example of a Simple Class in Java:
// Defining a class named Car
public class Car {
// Fields (attributes)
String model;
int year;
String color;
// Constructor to initialize the object's fields
public Car(String model, int year, String color) {
this.model = model;
this.year = year;
this.color = color;
}
// Method to display the car's information
public void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year + ", Color: " + color);
}
// Another method (behavior)
public void drive() {
System.out.println("The car is driving.");
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Toyota", 2020, "Red");
// Calling methods on the object
myCar.displayInfo(); // Output: Model: Toyota, Year: 2020, Color: Red
myCar.drive(); // Output: The car is driving.
}
}
Explanation:
Class Definition:
public class Car { ... }
defines a class namedCar
.- The class has three fields:
model
,year
, andcolor
, which represent the state of the car object.
Constructor:
public Car(String model, int year, String color)
is a constructor that initializes the fields of the class when an object is created. The constructor has the same name as the class and no return type.
Methods:
displayInfo()
anddrive()
are methods (behaviors). ThedisplayInfo()
method prints the car’s details, and thedrive()
method simulates the car’s driving behavior.
Creating Objects:
- In the
Main
class, the lineCar myCar = new Car("Toyota", 2020, "Red");
creates an object of theCar
class. This invokes the constructor to initialize the fields.
- In the
Calling Methods:
- After creating the object,
myCar.displayInfo()
andmyCar.drive()
are called to access the object's methods.
- After creating the object,
Key Features of Classes in Java:
1. Fields (Attributes or Properties):
- Fields represent the data that each object will store. They define the state of an object.
- Fields can have various access modifiers like
private
,public
,protected
, or package-private (no modifier).
private String model; // Only accessible within the class
2. Methods (Behaviors):
- Methods define the operations that an object of the class can perform.
- Methods can return values, or be
void
if they don’t return anything. - Methods can accept parameters to perform actions based on input.
public void drive() {
System.out.println("The car is driving.");
}
3. Constructors:
- Constructors are special methods used to initialize objects. They have the same name as the class and no return type.
- Java provides a default constructor if you don't define one, but once you create a custom constructor, the default one is not available unless explicitly defined.
public Car(String model, int year, String color) {
this.model = model; // 'this' refers to the current object's fields
this.year = year;
this.color = color;
}
4. Access Modifiers:
- Public: The class, field, or method is accessible from any other class.
- Private: The field or method is accessible only within its own class.
- Protected: The field or method is accessible within the same package or subclasses.
- Default (package-private): If no modifier is specified, the field or method is accessible within the same package.
Example with Access Modifiers:
public class Employee {
// Private fields (accessible only within this class)
private String name;
private int age;
// Constructor to initialize fields
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
// Public method to access private fields
public void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
// Getter for name (accessing private field)
public String getName() {
return name;
}
// Setter for name (modifying private field)
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee("John", 30);
emp.displayDetails(); // Output: Name: John, Age: 30
emp.setName("Mike"); // Modify the private field using setter
System.out.println(emp.getName()); // Output: Mike
}
}
In this example:
name
andage
are private fields, and can only be accessed or modified through public methods (getName()
andsetName()
).
Types of Classes in Java:
- Concrete Class: A regular class that can be instantiated (e.g., the
Car
class). - Abstract Class: A class that cannot be instantiated and is meant to be extended by other classes.
- Contains abstract methods (without implementation) that must be implemented by subclasses.
- Example:
abstract class Animal { abstract void sound(); }
- Final Class: A class that cannot be subclassed or extended. Marked with the
final
keyword. - Inner Class: A class defined within another class. Inner classes can access the members of the outer class.
Summary:
- A class in Java is a blueprint for creating objects. It defines attributes and behaviors that an object will have.
- A class contains fields (attributes), methods (behaviors), and constructors (to initialize objects).
- Objects are instances of a class and interact with the world through their methods and fields.
- Java supports access modifiers to control the visibility of class members.
- Constructors allow initializing an object's state, and methods define how the object behaves.
Classes are at the core of Java’s object-oriented approach, enabling modular, maintainable, and reusable code.