Class in Java
In Java, a class is a blueprint for creating objects, providing the initial values for state (attributes) and implementations of behavior (methods). Classes are fundamental to Java’s object-oriented nature. Each class in Java is defined with a set of attributes and methods encapsulated within it. Attributes store data while methods define actions that can be performed on the data. A class is declared using the class keyword followed by the class name and a body enclosed by braces. For instance, class Car defines a new class named Car. Classes support inheritance, allowing one class to acquire the properties and methods of another. This is crucial for promoting code reusability and system manageability. Essentially, classes serve as the building blocks of Java applications, enabling the creation of complex systems through simple, manageable, and reusable code components.
Functions of Class in Java:
- Encapsulation:
Classes encapsulate data (attributes) and code (methods) into a single unit. This encapsulation helps to protect the data from unauthorized access and misuse, ensuring that objects maintain a valid state.
-
Data Abstraction:
Classes provide a level of abstraction that allows the programmer to hide complex implementation details from the user. This means users interact with objects through a well-defined interface without needing to understand the underlying complexities.
- Inheritance:
Classes enable inheritance, a mechanism by which one class can inherit the properties and behaviors (methods) of another. This promotes code reusability and can lead to a hierarchical classification of classes, often reflecting real-world relationships.
- Polymorphism:
Through classes, Java implements polymorphism, allowing methods to do different things based on the object that is calling them. This is typically achieved through method overriding and overloading, which enhances flexibility in code execution.
-
Object Creation:
Classes act as templates for creating objects. Each object created (an instance) from a class has the structure defined by the class, with its own set of data values, ensuring consistent behavior across objects.
-
Method and Property Management:
Classes manage methods and properties, organizing behaviors and state-related data. This management facilitates clearer, more logical, and manageable code.
-
Constructor Functions:
Classes define constructors, special methods called when creating a new object. Constructors initialize new objects and can be overloaded to allow different ways of initializing objects based on different inputs.
-
Static Members:
Classes can have static methods and properties, which belong to the class rather than any object of the class. Static members are shared among all instances of a class, useful for implementing behavior and states that should be common to all instances.
Example of Class in Java:
Below is a class named Car that includes several typical features such as private fields, constructors, methods, and a static member:
public class Car {
// Private fields
private String make;
private String model;
private int year;
// Static member
public static int numberOfCars = 0;
// Constructor to initialize the Car object
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
numberOfCars++; // Increment static count of cars
}
// Method to display the details of the car
public void displayInfo() {
System.out.println(“Car Make: ” + make);
System.out.println(“Car Model: ” + model);
System.out.println(“Car Year: ” + year);
}
// Getter for Make
public String getMake() {
return make;
}
// Setter for Make
public void setMake(String make) {
this.make = make;
}
// Main method to create and manipulate Car objects
public static void main(String[] args) {
Car myCar = new Car(“Toyota”, “Corolla”, 2020);
myCar.displayInfo();
// Change the make of the car
myCar.setMake(“Honda”);
myCar.displayInfo();
// Display number of cars
System.out.println(“Total number of cars: ” + numberOfCars);
}
}
Explanation:
- Fields:
make, model, and year are fields that store the state of the Car objects. These are marked private to encapsulate and protect them from direct access from outside the class.
-
Static Member:
numberOfCars keeps track of how many Car objects have been created. It’s shared across all instances of the class.
- Constructor:
The constructor initializes new objects with a make, model, and year. It also increments the numberOfCars static variable each time a new object is created.
- Methods:
displayInfo is a method to output the details of the car. Getter and setter methods for make allow controlled access to modify and retrieve the make of the car.
-
Main Method:
This is where the program starts executing. It creates an instance of Car, modifies its state, and prints details to the console.
Interface in Java
In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in interfaces are abstract by default, which means they do not have a body and must be implemented by classes that choose to implement the interface. Interfaces are declared using the interface keyword. They are used to define a contract for what a class can do, without specifying how it does it. This abstraction allows for a form of multiple inheritance, as a class can implement multiple interfaces. Interfaces are particularly useful for defining roles that different classes can play, regardless of where they exist in the class hierarchy, promoting a high degree of loose coupling in software designs.
Functions of Interface in Java:
- Abstraction:
Interfaces provide abstraction by allowing the declaration of methods that must be implemented by classes, without providing their implementation. This means that the details of each method’s operations are hidden and are separately defined in implementing classes.
-
Multiple Inheritance:
Java does not support multiple inheritance of classes but allows a class to implement multiple interfaces. This feature helps in avoiding the complexity and ambiguity caused by multiple inheritance of classes while still allowing an object to inherit many types of capabilities.
-
Loose Coupling:
Interfaces help in achieving loose coupling between classes by serving as a middle layer. Classes can communicate through interfaces rather than directly, making it easier to change the implementation without affecting dependent classes.
-
Program to an Interface, not an Implementation:
This design principle encourages coding against interface references, which can then be instantiated with any number of implementations, thus providing flexibility in the choice of the implementing class at runtime.
- Polymorphism:
Interfaces facilitate polymorphism in Java. A single interface reference can point to any of the multiple implemented classes, allowing methods to be invoked on the interface that will perform differently depending on the object’s actual class type.
- Standardization:
Interfaces are a way to standardize and enforce certain methods across multiple classes. Implementing an interface guarantees that a particular class offers specific behavior, promoting consistency.
-
Enhance Security:
By separating the definition of methods from their implementation, interfaces help enhance security. Sensitive methods can be defined in an interface in a controlled manner without exposing the internals of their implementations.
-
Support for Lambda Expressions and Functional Programming:
From Java 8 onwards, interfaces can have default and static methods which help in bridging the gap between functional programming and object-oriented programming. Interfaces can now have method bodies, allowing for lambda expressions to be used more effectively.
Example of Interface in Java:
We’ll define an interface Vehicle with a couple of methods, and then create a couple of classes that implement this interface.
Interface Definition
public interface Vehicle {
// Interface method (does not have a body)
void start();
void stop();
// A default method (has a body)
default void honk() {
System.out.println(“Honking…”);
}
}
Implementing Classes
Car Class:
public class Car implements Vehicle {
@Override
public void start() {
System.out.println(“Car starting”);
}
@Override
public void stop() {
System.out.println(“Car stopping”);
}
}
Bike Class:
public class Bike implements Vehicle {
@Override
public void start() {
System.out.println(“Bike starting”);
}
@Override
public void stop() {
System.out.println(“Bike stopping”);
}
}
Main Class to Test
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBike = new Bike();
myCar.start();
myBike.start();
myCar.honk(); // Calling the default method
myBike.honk(); // Calling the default method
myCar.stop();
myBike.stop();
}
}
Explanation
-
Interface Vehicle:
This interface declares two abstract methods (start and stop) that must be implemented by any class that implements the interface. It also includes a default method honk, which provides a common method implementation that can be used or overridden by implementing classes.
-
Classes Car and Bike:
Both classes implement the Vehicle interface. Each class provides its own implementation of the start and stop methods.
-
Default Method:
The honk method is a default method in the Vehicle interface. This means it has a default implementation that does not need to be overridden by implementing classes, although it can be if desired.
-
Main Class:
In the Main class, instances of Car and Bike are created and their methods are called. This demonstrates polymorphism since the interface Vehicle is used as the type for both myCar and myBike.
Key differences between Class in Java and Interface in Java
Aspect | Class | Interface |
Type of Entity | Blueprint of objects | Contract for classes |
Inheritance | Single inheritance | Multiple inheritance |
Implementation | Provides implementation | Does not provide implementation |
Method Body | Can have method body | No method body (except default and static methods) |
Constructors | Has constructors | No constructors |
Instantiation | Can be instantiated | Cannot be instantiated |
Access Modifiers | Can have any access modifier | Public or none (implicitly public) |
Fields | Can contain instance fields | Only static and final fields |
Method Types | All method types allowed | Only abstract, default, static |
Usage | Defines “what” and “how” | Defines “what”, not “how” |
Storage for Data | Can store data | Cannot store data |
Extension | Can extend one class | Can extend multiple interfaces |
Keywords | class keyword | interface keyword |
Default Methods | No default methods | Allows default methods |
Static Methods | Can have static methods | Can have static methods |
Key Similarities between Class and Interface in Java
-
Type Definitions:
Both are used to define types in Java. Classes define new data types by specifying the structure and behavior of objects, whereas interfaces define a type by specifying a set of method signatures that other classes can implement.
-
Can Contain Methods:
Both classes and interfaces can contain methods. In Java 8 and later, interfaces can also have default and static methods, which include implementations, similar to methods in classes.
-
Support for Modifiers:
Both can use access modifiers. While class fields and methods can be declared with any access modifiers (public, protected, private), interface methods and fields are public by default if no access modifier is explicitly stated.
-
Use in Polymorphism:
Both can be used to implement polymorphism in Java. Interfaces provide a way to achieve polymorphism through method overriding in different classes that implement the interface. Classes achieve polymorphism through methods that can be overridden in subclasses.
-
Part of Inheritance Hierarchy:
Both can be part of an inheritance hierarchy. A class can inherit from another class, and an interface can extend another interface. Additionally, a class can implement multiple interfaces, and an interface can extend multiple interfaces.
-
Syntax Elements:
Both use similar syntax elements in Java. For example, they both use braces {} to enclose their bodies, and their members are declared within these braces.
-
Can be Extended or Implemented:
Just as classes can be extended, interfaces can be extended by other interfaces. A class can implement any number of interfaces, which is akin to the class extending functionality.
- Documentation:
Both are equally subject to documentation best practices. Developers are encouraged to document classes and interfaces using JavaDoc, which aids in understanding the purpose and use of both.