Java serves as an object-oriented programming language, where the fundamental principle revolves around decomposing intricate problems into smaller entities.
An object, in this context, refers to any entity characterized by both a state and a set of behaviors. Take a bicycle as an example:
States: These encompass conditions like being idle or in first gear.
Behaviors: These pertain to actions such as braking or accelerating.
Before delving into objects, it's essential to gain an understanding of classes in the context of Java.
Classes:
A class is a blueprint or template for creating objects. It defines the structure and behavior that its objects will have.
Classes in Java are declared using the class keyword, followed by the class name.
Here's a simple example of a Java class:
In Java, a class can encompass the following elements:
1. Fields: These represent variables or data members that store the state of objects created from the class.
2. Methods: These are functions or procedures associated with the class that define its behaviors and operations.
3. Constructors: Constructors are special methods used to initialize objects when they are created. They set the initial state of the object.
4. Blocks: Java classes can include initialization blocks, which are sections of code executed when an instance of the class is created. There are two types of blocks: instance initialization blocks and static initialization blocks.
5. Nested class and interface: A class in Java can contain other classes (nested classes) or interfaces. These nested elements can help in organizing and encapsulating related functionality within the class.
These elements collectively define the structure, behavior, and functionality of objects created from the class.
In Java, you declare a class using the following syntax:
[access_modifier] class ClassName {
// Fields (variables)
// Constructors
// Methods
}
Here's a breakdown of the components:
[access_modifier]: This is an optional access modifier like public, private, protected, or package-private (no modifier). It determines the visibility of the class. If omitted, the default access modifier is package-private.
class: The keyword used to declare a class.
ClassName: The name you choose for your class. It should follow Java's naming conventions (typically using CamelCase).
Inside the class declaration, you can include fields (variables), constructors, and methods that define the behavior and properties of objects created from the class.
Here's a simple example of a class declaration:
public class Person {
// Fields
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
In this example, we've declared a class called Person with fields, a constructor, and a method.
Java is indeed an object-oriented programming language, and its core principle revolves around breaking down complex problems into smaller, more manageable entities.
An object, in this context, represents any entity characterized by both a state and a set of behaviors. For instance, consider a bicycle as an example:
1.States: These encompass conditions such as being idle or in the first gear.
2.Behaviors: These pertain to actions like braking or accelerating.
3.Identity in object-oriented programming is usually established through a unique identifier, commonly known as an ID. This ID value remains hidden from external users but plays a vital role within the JVM (Java Virtual Machine) to uniquely distinguish and identify each object.
Before we delve further into objects, it's essential to first gain an understanding of classes in Java.
Object Creation:
Once you have a class defined, you can create objects (instances) of that class. You do this using the new keyword followed by a constructor call. The constructor initializes the object.
For example:
// Creating objects of the Person class
Person person1 = new Person("Abhay", 30);
Person person2 = new Person("Ranjeet", 25);
In this example, we've created two Person objects, person1 and person2.
Ways To Intialize Object
In Java, you can initialize an object in several ways, depending on your specific requirements and the design of your classes. Here are the common ways to initialize an object:
By reference variable
By method
By constructor
class Student {
int id;
String name;
}
class TestStudent2 {
public static void main(String args[]) {
Student s1 = new Student(); // Creating an instance of the Student class
s1.id = 756; // Assigning a value to the 'id' field
s1.name = "Abhay"; // Assigning a value to the 'name' field
System.out.println(s1.id + " " + s1.name); // Printing the 'id' and 'name' fields with a space in between
}
}
Output:-
756 Abhay
In this example, we create two instances of the Student class and set their values using the insertRecord method. Afterward, we display the data stored in these objects by calling the displayInformation method.
class Student {
int rollno;
String name;
void insertRecord(int r, String n) {
rollno = r;
name = n;
}
void displayInformation() {
System.out.println(rollno + " " + name);
}
}
class TestStudent4 {
public static void main(String args[]) {
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(100, "Abhay");
s2.insertRecord(110, "Ranjeet");
s1.displayInformation();
s2.displayInformation();
}
}
Output
100 Abhay
110 Ranjeet
class Employee {
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id = i;
name = n;
salary = s;
}
void display() {
System.out.println(id + " " + name + " " + salary);
}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
e1.insert(101, "Vaishu", 45000);
e2.insert(102, "Ranjeet", 35000);
e3.insert(103, "Abhay", 85000);
e1.display(); e2.display();
e3.display();
}
}
Output
101 Vaishu 45000.0
102 Ranjeet 35000.0
103 Abhay 85000.0
In Java, methods are blocks of code that perform a specific task or set of tasks. They are defined within classes and are essential building blocks of object-oriented programming. Here are some key aspects of methods in Java:
1.Method Declaration:
A method is declared within a class using the following syntax:
return_type method_name(parameters) {
// method body
}
return_type specifies the type of value that the method will return (if any). If the method doesn't return anything, you can use void as the return type.
method_name is the name of the method.
parameters are the inputs that the method accepts (if any). Parameters are enclosed in parentheses and can be zero or more.
2.Method Signature:
The method name and its parameter list together form the method's signature. Method overloading is allowed in Java, which means you can have multiple methods with the same name but different parameter lists.
3.Method Body:
The method body contains the statements that define the functionality of the method. It is enclosed in curly braces {}.
4.Return Statement:
If a method has a non-void return type, it must use the return statement to return a value of the specified type.
For example:
int add(int a, int b) {
return a + b;
}
5.Method Invocation:
You can call (or invoke) a method using the dot notation, followed by the method name and arguments (if any).
For example:
int result = add(5, 3);
6.Access Modifiers:
You can use access modifiers (e.g., public, private, protected, or package-private/default) to control the visibility and accessibility of methods.
7.Static Methods:
Static methods are associated with the class itself rather than with instances of the class. They are declared using the static keyword.
8.Method Overriding:
Inheritance allows you to override methods in a subclass to provide a specific implementation. This is achieved using the @Override annotation.
Varargs:
Java supports variable-length argument lists using varargs. A varargs parameter allows you to pass a variable number of arguments to a method.
Here's an example of a Java method:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = calc.add(5, 3);
System.out.println("Sum: " + sum);
}
}
In this example, the add method takes two integer parameters, adds them, and returns the result. The main method demonstrates how to call the add method to perform addition.