What is Class Definition in Java
A Class is a template for creating objects in object-oriented languages like Java. Users define classes to build a framework where data and behavior of the objects can be created from the Class definition. These classes are fundamental components of Object-Oriented Programming. Java developers use class definitions to compose objects in their programs.
Table of Contents
Java Classes
Classes represent real-world concepts and define their properties (fields) and behaviors (methods). A class provides a template from which an object can be instantiated. Classes promote code reusability, maintainability, and extensibility by creating objects with similar attributes and behavior.
Properties of Java Classes
These are various properties of Java.
- A class is simply a template with properties and behavior. A class can contain a set of methods and different data types.
- Class is not a real-world entity.
- The class has no memory, but objects can have memory.
- The class has various fields like method, data member, interface, constructor, nested loops, etc.
- Classes provide various properties such as flexibility and modularity, encapsulation and abstraction, inheritance, and polymorphism.
Class Declaration in Java
In Java, a class can have various components, like fields, methods, constructors, blocks, nested classes, interfaces, etc.
access_modifier class
{
data member;
method;
constructor;
nested class;
interface;
}
For example,
// Java Program for class example
public class Car {
// data members (instance variables)
String make;
String model;
int year;
// constructor to initialize Car objects
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// method to display car details
public void displayDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
public static void main(String[] args) {
// creating an object of Car
Car myCar = new Car("Toyota", "Camry", 2022);
// displaying car details
myCar.displayDetails();
}
}
Output:
Explanation:
- Create a class named Car.
- Define three variables within the Car class: make, model, and year.
- Create a constructor within the Car class to initialize the make, model, and year variables.
- Define a method named display within the Car class to display the car’s information (make, model, and year).
- Create an object named myCar of the Car class, passing “Toyota” as the make, “Camry” as the model, and “2022” as the year to the constructor.
- Call the display method on the myCar object to display the make, model, and year values.
Elements of Java Classes
Generally, class declarations consist of the following elements arranged in sequence:
- Modifiers: Classes can have public access or default access.
- Class keyword: Used to define a class.
- Class name: Should start with a capital letter.
- Superclass (if any): Name of the superclass, preceded by the keyword extends. A class can only inherit from one superclass.
- Interfaces (if any): Comma-separated list of interfaces implemented by the class, preceded by the keyword implements. A class can implement multiple interfaces.
- Body: The class body enclosed within braces, { }.
Constructors are utilized to initialize new objects, while fields define a class’s state and its objects. Methods, on the other hand, execute the behavior of a class and its objects.
1. Fields:
- Fields are instance variables that represent the state of objects. These are non-static variables.
- Fields are declared within the class but outside any method, constructor, or block.
- Fields can have different data types (i.e., int, String, boolean, etc.) and access modifiers (i.e., public, private, protected, default, etc.).
2. Methods:
- Methods represent the behavior of an object, encompassing actions and operations that an object can perform.
- Methods can have different data types (i.e., int, String, boolean, etc.) and access modifiers (i.e., public, private, protected, default, etc.).
- Methods can be overloaded.
3. Constructor:
- Constructors are special methods. Constructors have the same name as the class name and do not have a return type, not even void.
- When you create an object, the program automatically calls constructors to initialize it.
- Constructors can be overloaded.
Real-time applications use different types of classes, like nested classes, anonymous classes, and lambda expressions. These are indeed advanced concepts in Java used for specific purposes.
Java Objects
In Java programming, the object is primary in Object-Oriented Programming (OOP). An object in Java represents a real-world concept. It is an instance of a class that encapsulates data (attributes) and behavior (methods). Objects are the building blocks of Java programs.
Key Components of Java Objects:
Java programs can have many objects. These can have state, behavior, and identity.
- Identity: Each object in Java has a unique identity that is distinguished from other objects.
- State: An object’s attributes determine its state. These attributes include information that describes the state of the object right now.
- Behavior: The object class defines methods that encapsulate operations which objects can perform, these methods are known as behaviors.
Example of Java Object
public class Person {
// Instance Variables
String name;
int age;
// Constructor Declaration
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to Display Person Information
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Creating an Object of Person class
Person person1 = new Person("John", 30);
// Displaying Information of the Person Object
System.out.println("Person Information:");
person1.displayInfo();
}
}
Output:
Explanation:
- Person class:
- Contains two variables: name and age.
- The constructor initializes these variables when creating an object.
- Includes a method named display to print the name and age values.
- Main function:
- Creates an object named person1 of type Person.
- Initializes the name variable of person1 with “John” and age variable with 30.
- Calls the display method on the person1 object to display the information (name and age).
Declaring Objects in Java
In Java, declaring objects, also known as instantiating a class, involves creating instances of a class to work with. You can utilize the attributes and behaviors defined within the class blueprint. Let’s see how to declare objects in Java.
Syntax:
To declare an object in Java, you use the following syntax:
ClassName objectName = new ClassName();
Here, ClassName is the name of the class you want to instantiate, and objectName is the name you assign to the object instance.
For example:
Consider a simple class named Car:
public class Car {
String make;
String model;
int year;
}
To declare an object of the Car class, you can use the following code:
Car myCar = new Car();
myCar is the object’s name, and new Car() creates a new instance of the Car class.
Initializing Object Properties:
Once the object is declared, you can access its properties (fields) and methods using the dot (.) notation. For example, you can assign values to the object attributes:
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2022;
We set the make, model, and year attributes of myCar to specific values
Using Object Methods:
You can also invoke methods defined within the class on the object. For example, if the Car class had a method named drive(), you could call it like this:
myCar.drive();
Multiple Object Declarations:
You can declare multiple objects of the same class using the same syntax:
Car car1 = new Car();
Car car1 = new Car();
In this case, car1 and car2 are separate instances of the Car class.
Initializing a Java Object
During object initialization, allocating memory for the object and setting its initial state is important. You need to call the constructor to initialize its member variables. Let’s see how to initialize Java objects.
1. Using Constructors:
It is the primary method for initializing objects in Java. Constructors are special methods within a class. They initialize the state of newly created objects. When creating an object, the new keyword calls an appropriate constructor to initialize it.
For example,
public class Car {
String make;
String model;
int year;
// Constructor Declaration
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Other methods and variables...
}
The Car class has a constructor. It accepts three parameters: make, model, and year. When you create a new Car object, you must pass values for these three parameters to initialize the object.
Note that constructors have the same name as their class names under the CamelCase naming convention. Constructors return nothing, even void types.
2. Initializing an Object:
You can initialize an object like this:
Car myCar = new Car("Toyota", "Camry", 2022);
The myCar is an object and reference variable that points to a new Car object created using the constructor. The constructor initializes the Car object’s make, model, and year attributes with the provided values, i.e., “Toyota,” “Camry,” and 2022, respectively.
3. Default Constructors:
Suppose a class does not explicitly define any constructors. Java automatically provides a default constructor with no parameters. If not overridden, this default constructor initializes the object with default values or performs no initialization.
For example,
public class Person {
String name;
int age;
// Default Constructor
public Person() {
name = "Unknown";
age = 0;
}
// Other methods and variables...
}
The Person class has a default constructor that initializes the name attribute to “Unknown” and the age attribute to 0.
4. Initializing Objects Inline:
You can also initialize objects inline. You can do this using object initialization blocks and directly setting values to member variables after object creation.
For example,
Car myCar = new Car();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 2020;
Prefer constructors over other methods since they ensure proper object initialization during creation.
Techniques to Create an Object of a Class
You can create objects in Java in four ways. But it would help if you used a new keyword in these ways to create objects.
1. Using new keyword
You can create an object in Java using a new keyword. It is a widespread way to create objects.
For example,
// creating object of class Car
Car myCar = new Car();
We have created an object myCar of class Car type.
2. Using String className (Class.forName)
Using Java, we can create an object in a pre-defined class in the java.lang package with the class name. You can use this method to retrieve the class object associated with the name you provide as a string input. You must provide a qualified name for a class. It will return a new class instance with the given string name.
For example,
// creating object of public class Car
// consider class Car present in com.p1 package
Car myCar = (Car) Class.forName("com.p1.Car").newInstance();
3. Using the clone method
The object class has a clone() method that creates and returns a copy of the object.
For example,
// creating object of class Car
Car myCar = new Car();
// creating clone of above object
Car yourCar = (Car)myCar.clone();
4. De-serialization
You can read an object using the De-serialization technique in Java.
For example,
FileInputStream fileInputStream = new FileInputStream(filename);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Car myCar = (Car)objectInputStream.readObject();
5. Creating multiple objects of the same class
It can create multiple objects of the same type using a single reference variable. It reduces memory wastage and promotes efficient memory management. The garbage collector collects objects that are no longer in use.
For example,
Car myCar = new Car();
myCar = new Car();
In the inheritance system, we use parent class reference variables to store the sub-class object. In this case, we can switch to different subclass objects using the same referenced variable.
For example,
class Vehicle {}
class Car extends Vehicle {}
class Truck extends Vehicle {}
public class Example {
// using Car object
Vehicle myVehicle = new Car();
// using Truck object
myVehicle = new Truck();
}
Difference between Java Class and Objects
Class | Object |
Blueprint for creating objects | An instance of a class |
No memory allocated when declared | Memory allocated upon creation |
Logical entity | Physical entity |
Represents a group of similar objects | Represents a specific real-world entity |
It can be declared only once | Can be created multiple times |
Car, Animal, Employee | BMW, Dog, John (specific instances) |
Best Practices for Using Java Classes and Objects
1. Naming Convention
Always name classes in PascalCase and Variables and methods in camelCase. Use meaningful and descriptive names for classes, variables, and methods.
- Please capitalize the first letter of each word in PascalCase.
- In camelCase, the first letter of the first word is lowercase, and subsequent words start with uppercase letters.
For example, in this Java code, the class name (UserProfile) is according to PascalCase. Methods (getUserName) and variables (userName) are according to camelCase.
// Class named in PascalCase
public class UserProfile {
// Variables and methods named in camelCase
private String userName;
// Constructor
public UserProfile(String userName) {
this.userName = userName;
}
// Method to get the user name
public String getUserName() {
return userName;
}
}
Note that there is an exception here that the constructor (UserProfile) is a special method that should have the same name as the class name (UserProfile). It means constructors should also write according to PascalCase but not camelCase.
2. Encapsulation
Use encapsulated data and set public for getter and setter methods to access and modify them.
Encapsulation, as the name suggests, binds data (variables) and methods (functions).
It hides data and members and also restricts direct access to some components. Thus, to do this, you need public getter and setter methods to access and modify private fields.
For example, in this BankAccount class, you can not directly read and write balances because of the private field. However, you can do this using the getBalance and deposit method. These are getter and setter, respectively.
public class BankAccount {
private double balance;
// Getter method to access the balance
public double getBalance() {
return balance;
}
// Setter method to modify the balance
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
}
Without these getter and setter methods, you can not access the balance field because of private property.
3. Interfaces for Abstraction
Use interfaces for abstraction to specify contracts between classes. In Java, both the abstract classes and the interfaces can be used to achieve abstraction.
Note that interfaces can provide 100% abstraction. Meanwhile, the abstract class provides only partial abstraction. However, abstract classes can have concrete functions while declaration, but Interfaces may not.
For example, in this Sedan class, we used the Car interface:
// Interface defining the car behavior
public interface Car {
void start();
void stop();
}
// Class implementing Car interface
public class Sedan implements Car {
@Override
public void start() {
System.out.println("Sedan car started");
}
@Override
public void stop() {
System.out.println("Sedan car stopped");
}
}
// Creating an instance of Sedan
Car myCar = new Sedan();
4. Composition over Inheritance
Favor composition over inheritance to achieve code reuse. In Composition, we create objects by combining simpler objects. Meanwhile, in inheritance, we create new classes based on existing classes. Instead of inheriting behavior from parent classes. It would help if you used composing classes by including instances of other classes as fields within your class. Composition over inheritance provides code reuse, modularity, and flexibility.
We achieve polymorphic behavior and code reuse by containing instances of other classes (composition) rather than inheriting from them.
For example, in this code, the Car class uses an instance of the Engine class without any inheritance. It is called the composition of the class.
// Engine class
class Engine {
public void start() {
System.out.println("Engine started");
}
}
// Car class using composition of Engine class
class Car {
private Engine engine;
public Car() {
this.engine = new Engine(); // Instance of Engine class
}
public void start() {
engine.start(); // method of Engine class
System.out.println("Car started");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start();
}
}
Output:
5. Unit Testing
To ensure that your classes and objects behave as intended, write unit tests. Just like, you write unit tests for other code to test their behavior of the code. You can also write unit test code for Java Classes code to test the smallest functional unit of code.
Conclusion
Java OOPs’ fundamental ideas are Java classes and objects. Classes are templates for creating objects with data (properties) and behavior (methods). We first write a class; then, we can create objects for this class. For example, an Animal is a class, and its objects are a dog, cat, cow, etc. There are certain rules for naming conventions. You can use CamelCase to declare class and constructor methods. Constructors are special methods that have the same name as their class name. It would help if you used camelCase to name other methods and variables inside a class.
As other concepts of OOPS are used. Encapsulation provides data hiding and access control. Abstraction is used to define interfaces and contracts between classes. You should use composition rather than inheritance, which provides code reusability and coupling.
Frequently Asked Questions (FAQs)
Q1- What are Anonymous Objects in Java?
Answer: Anonymous objects are objects created without assigning them to a variable. Anonymous objects prove useful for swiftly executing method calls and are thrown away after use. They find extensive applications across various libraries.
For example, when a button gets clicked, we create an anonymous object of the EventHandler class to invoke the handle method.
btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
Q2- Which OOPs ideas apply to Java classes?
Answer: In Java classes, you can use various OOPs concepts:
- Encapsulation to hide implementation details. Abstraction to showcase essential features
- Inheritance to inherit properties and behaviors from other classes.
- Polymorphism treats objects of different classes as the same type of object, allowing them to be used interchangeably.
They are leveraging these Object-Oriented Programming (OOP) concepts. These concepts ensure well-structured and modular Java class designs, promoting code reusability, maintainability, and extensibility.
Q3- What are the different ways to create an object in Java?
Answer: Different techniques to create an object in Java include using the new keyword, newInstance() method, clone() method, deserialization, and factory method.
Recommended Articles
We hope that this EDUCBA information on “Class Definition in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.