- Java Programming Basics
- Java Tutorial
- Java Environment Setup
- Java Separators
- Java Data Types
- Java Variables
- Java Variable Scope
- Java Type Casting
- Java Operators
- Java Increment Decrement
- Java Left Shift
- Java Right Shift
- Java Bitwise Operators
- Java Ternary Operator
- Java Control Statements
- Java if-else statement
- Java for Loop
- Java while Loop
- Java do-while Loop
- Java switch Statement
- Java break Statement
- Java continue Statement
- Java Popular Topics
- Java Arrays
- Java Multidimensional Array
- Java Strings
- Java Methods
- Java Date and Time
- Java Exception Handling
- Java File Handling
- Java OOP
- Java Classes and Objects
- Java Constructors
- Java Constructor Overloading
- Java Object as Parameter
- Java Returning Objects
- Java Encapsulation
- Java Abstraction
- Java Inheritance
- Java Polymorphism
- Java Packages
- Java Import Statement
- Java Multithreading
- Java Suspend Resume Stop Thread
- Java Programming Examples
- Java Programming Examples
Java classes and objects (with examples)
Java is a well-known object-oriented programming language used to create a variety of applications. Object-oriented programming is founded on the idea of objects, which are actual instances of classes. A class is a blueprint in Java that specifies the properties and methods of objects. Java programmers must grasp classes and objects. This post introduces Java classes and objects with examples.
A class in Java is a blueprint for creating objects. It specifies a set of attributes (or data members) and behaviors (or methods) that a class object can have. Multiple instances (or objects) of a class can be created, each with its own set of attribute values, and each object can invoke the class's methods. As an example:
public class MyClass { }
This class serves as a template for creating objects even though it lacks data members and methods. You could, for instance, do the following to make an instance of this class:
MyClass myObject = new MyClass();
"myObject" is a "MyClass" object. This object can be used as a placeholder or marker in your code despite having no attributes or behaviors. To add functionality or create subclasses, you can extend this class.
In other words, a class develops a logical framework that establishes the relationships among its members and produces a new data type that can be used to create objects. A class instance is produced when an object of that class is declared. A class is thus a logical construct. An object occupies space in memory and has a physical reality. Any idea you want to use in a Java program needs to be contained within a class.
The class keyword in Java
The "class" keyword is used to declare or define a new class in Java. As an example:
public class MyClass {
// block of code to define this class
}
The new keyword in Java
The "new" keyword is used to create a new instance of a class. As an example, let's create an instance of the previously created class named "MyClass."
MyClass obj = new MyClass();
Java class and object example
Consider the following Java program as an example demonstrating the class and object.
public class ClassObjectExample { private int res; public int findSum(int a, int b) { res = a + b; return res; } public static void main(String[] args) { ClassObjectExample myObject = new ClassObjectExample(); int numOne = 10, numTwo = 20, add; add = myObject.findSum(numOne, numTwo); System.out.println("Sum of " + numOne + " and " + numTwo + " = " + add); } }
Sum of 10 and 20 = 30
This Java program is made up of a class called "ClassObjectExample" that has a private integer variable called "res" and a public method called "findSum" that takes two integer parameters and returns their sum. The method returns the same value as the sum of the two integers assigned to the private variable "res." The "new" keyword is used in the main method to create an object of the "ClassObjectExample" class. The variable "myObject" holds the object reference. Declare and assign values to two integer variables named "numOne" and "numTwo." The "findSum" method is invoked on the "myObject" object, with the variables "numOne" and "numTwo" as arguments. The result is saved in the variable "add." Finally, using the "System.out.println()" statement, the sum is printed to the output console.
The previous program is a very basic example demonstrating class and object in Java. Now let's level up with the following program:
public class ClassObjectExample { private String name; private int age; private String gradeLevel; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setGradeLevel(String gradeLevel) { this.gradeLevel = gradeLevel; } public String getName() { return name; } public int getAge() { return age; } public String getGradeLevel() { return gradeLevel; } public static void main(String[] args) { ClassObjectExample student1 = new ClassObjectExample(); student1.setName("William"); student1.setAge(16); student1.setGradeLevel("Junior"); ClassObjectExample student2 = new ClassObjectExample(); student2.setName("Edwin"); student2.setAge(17); student2.setGradeLevel("Senior"); System.out.println(student1.getName() + " is a " + student1.getGradeLevel() + " in high school and is " + student1.getAge() + " years old."); System.out.println(student2.getName() + " is a " + student2.getGradeLevel() + " in high school and is " + student2.getAge() + " years old."); } }
William is a Junior in high school and is 16 years old. Edwin is a Senior in high school and is 17 years old.
This program defines "ClassObjectExample" as a class with three private instance variables: "name", "age", and "gradeLevel." These variables are encapsulated within the class, which restricts their access and modification to the class's public methods. The class also contains six public methods, including three setter methods (setName, setAge, and setGradeLevel) to set the instance variables' values and three getter methods (getName, getAge, and getGradeLevel) to retrieve them.
Two instances of the "ClassObjectExample" class are created in the program's main method, one for each student. These objects are created using the "new" keyword. The values of the objects' instance variables are set using the setter methods after they have been created. Following the values' retrieval using getter methods, System.out.println statements are used to print them to the output console.
Advantages of classes in Java
- Encapsulation: Java classes enable encapsulation, which allows the implementation specifics of a class to be shielded from other program elements. This enhances the code's security and maintainability.
- Reusability: Classes encourage the reuse of code. A class can be used to create any number of objects with the same properties and behaviors once it has been defined. Coding becomes easier and more efficient as a result.
- Java supports inheritance, allowing new classes to be based on existing classes and to inherit their properties and methods. This can make the code more extensible and modular by reducing code duplication.
- Java supports polymorphism, a feature that enables objects of various classes to be handled as though they were objects of the same class. The code could become more flexible and cleaner as a result.
Disadvantages of classes in Java
- Complexity: Classes, particularly those that are poorly made or applied improperly, can add complexity to a program. This could make it more challenging to read, maintain, and debug the code.
- Overhead: When creating a class, some processing and memory costs are incurred. This might be a problem on devices with limited resources or in performance-critical applications.
- Lack of extensibility: If classes are not intended to be extensible, they may lack flexibility. It can be challenging to change a class after it has been defined without having an impact on other program elements.
- Learning curve: For newcomers, understanding classes can be challenging. Procedural programming requires a different way of thinking than object-oriented programming, which can take some practice to master.
« Previous Tutorial Next Tutorial »