Module 1.Docx
Module 1.Docx
that use objects in programming. They use objects as a primary source to implement what is
to happen in the code. Objects are seen by the viewer or user, performing tasks you assign.
Example:
Java// Use of Object and Classes in Java import java.io.*; class Numbers { // Properties
private int a; private int b; // Methods public void sum() { System.out.println(a + b); } public
void sub() { System.out.println(a - b); } public static void main(String[] args) { // Creating
Instance of Class // Object Numbers obj = new Numbers(); // Assigning Values to the
Properties obj.a = 1; obj.b = 2; // Using the Methods obj.sum(); obj.sub(); } }
Output
3 -1
It is a simple example showing a class Numbers containing two variables which can be
accessed and updated only by instance of the object created.
Java Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. Using classes,
you can create multiple objects with the same behavior instead of writing their code multiple
times. This includes classes for objects occurring more than once in your code. In general,
class declarations can include these components in order:
1. Modifiers: A class can be public or have default access (Refer to this for details).
2. Class name: The class name should begin with the initial letter capitalized by
convention.
3. Body: The class body is surrounded by braces, { }.
Java Object
An Object is a basic unit of Object-Oriented Programming that represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
The objects are what perform your code, they are the part of your code visible to the
viewer/user. An object mainly consists of:
1. State: It is represented by the attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of
an object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact with other
objects.
4. Method : A method is a collection of statements that perform some specific task and
return the result to the caller. A method can perform some specific task without
returning anything. Methods allow us to reuse the code without retyping it, which is
why they are considered time savers. In Java, every method must be part of some
class, which is different from languages like C, C++, and Python.
Example:
Java` // Java Program to demonstrate // Use of Class and Objects // Class Declared public
class GFG {
}`
Output
For more information, please refer to the article – Classes and Object .
Method and Method Passing
A method is a collection of statements that perform specific tasks and return a result to the
caller. It can be declared with or without arguments, depending on the requirements. A
method can take input values, perform operations, and return a result.
Java// Class Method and Method Passing import java.io.*; class Student { // Properties
Declared int id; String name; // Printing Student public void printStudent() {
System.out.println("Id:" + id); System.out.println("Name:" + name); } } class GFG { public
static void main(String[] args) { Student obj = new Student(); obj.id = 1; obj.name = "ABC";
obj.printStudent(); } }
Output
Id:1 Name:ABC
4 Pillars of Java OOPs Concepts
-Concept-in-Java.webp)
1. Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or non-essential units are not displayed to the user. Ex: A car is viewed as
a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object, ignoring the irrelevant details. The properties and behaviors of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the object.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the car speed or applying brakes will stop the car, but he does not
know how on pressing the accelerator, the speed is actually increasing. He does not know
about the inner mechanism of the car or the implementation of the accelerators, brakes etc. in
the car. This is what abstraction is.
Note: In Java, abstraction is achieved by interfaces and abstract classes. We can achieve
100% abstraction using interfaces.
Example:
Java// abstract class abstract class GFG { // abstract methods declaration abstract void add();
abstract void mul(); abstract void div(); }
To learn more about the Abstraction refer to the Abstraction in Java article
2. Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together the code and the data it manipulates. Another way to think about encapsulation is
that it is a protective shield that prevents the data from being accessed by the code outside
this shield.
● Technically, in encapsulation, the variables or the data in a class is hidden from any
other class and can be accessed only through any member function of the class in
which they are declared.
● In encapsulation, the data in a class is hidden from other classes, which is similar to
what data-hiding does. So, the terms “encapsulation” and “data-hiding” are used
interchangeably.
● Encapsulation can be achieved by declaring all the variables in a class as private and
writing public methods in the class to set and get the values of the variables.
Example:
Java// Encapsulation using private modifier // Employee class contains private data // called
employee id and employee name class Employee { private int empid; private String ename; //
Setter methods public void set_id(int empid) { this.empid = empid; } public void
set_name(String ename) { this.ename = ename; } // Getter methods public int get_id() {
return empid; } public String get_name() { return ename; } } public class Geeks { public
static void main(String args[]) { Employee e = new Employee(); e.set_id(78);
e.set_name("John"); System.out.println("Employee id: " + e.get_id());
System.out.println("Employee Name: " + e.get_name()); } }
Output
3. Inheritance
● Superclass: The class whose features are inherited is known as superclass (also
known as base or parent class).
● Subclass: The class that inherits the other class is known as subclass (also known as
derived or extended or child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Example:
Java// base class or parent class or super class class A{ // parent class methods void
method1(){} void method2(){} } // derived class or child class or base class class B extends
A{ // Inherits parent class methods // child class methods void method3(){} void method4(){}
}
4. Polymorphism
Example:
Javasleep(1000) //millis sleep(1000,2000) //millis,nanos
Types of Polymorphism
Java// Java Program to Demonstrate // Method Overloading and Overriding // Parent Class
class Parent { // Method Declared public void func(){ System.out.println("Parent Method
func"); } // Method Overloading public void func(int a){ System.out.println("Parent Method
func " + a); } } // Child Class class Child extends Parent { // Method Overriding @Override
public void func(int a){ System.out.println("Child Method " + a); } } // Main Method public
class Main { public static void main(String args[]){ Parent obj = new Child(); obj.func(4); } }
Output
Child Method 4
● OOP promotes code reusability: By using objects and classes, you can create
reusable components, leading to less duplication and more efficient development.
● OOP enhances code organization: It provides a clear and logical structure, making
the code easier to understand, maintain, and debug.
● OOP supports the DRY (Don’t Repeat Yourself) principle: This principle
encourages minimizing code repetition, leading to cleaner, more maintainable code.
Common functionalities are placed in a single location and reused, reducing
redundancy.
● OOP enables faster development: By reusing existing code and creating modular
components, OOP allows for quicker and more efficient application development
Conclusion
The Object Oriented Programming (OOPs) concept in Java is a powerful way to organize and
write code. It uses key ideas like classes, objects, inheritance, polymorphism, encapsulation,
and abstraction to create flexible and reusable code.
By using the Java OOPs concept, programmers can build complex applications more
efficiently, making the code easier to manage, understand, and modify. Overall, Java’s OOPs
concepts help in creating robust and scalable software solutions.
OOPs helps in organizing and structuring code in a more manageable way, making it easier to
maintain and scale Java applications. It also promotes code reusability, modularity, and
flexibility, leading to efficient and robust software development.
The main principles of OOPs in Java are encapsulation, inheritance, polymorphism, and
abstraction. Encapsulation ensures that the internal state of an object is hidden and can only
be accessed through public methods. Inheritance allows one class to inherit properties and
behavior from another. Polymorphism enables objects to be treated as instances of their
parent class. Abstraction focuses on hiding the implementation details and showing only the
necessary information to the outside world.
In Java, OOPs is implemented through classes and objects. A class serves as a blueprint for
creating objects, which are instances of that class. Each object has its own set of attributes
(variables) and methods (functions). By following OOPs concepts like encapsulation,
inheritance, polymorphism, and abstraction, Java developers can design well-structured and
maintainable code.
Some advantages of using OOPs in Java include code reusability, modularity, flexibility,
scalability, and easier maintenance. OOPs enables developers to model real-world entities as
objects, leading to more intuitive and organized code. It also supports features like
inheritance and polymorphism, which enhance the extensibility and readability of Java
applications.
Sure! An example of OOPs concept implementation in Java is creating a ‘Car’ class with
attributes like ‘make’, ‘model’, and ‘year’, along with methods like ‘start()’, ‘accelerate()’,
and ‘stop()’. By instantiating objects from the ‘Car’ class and calling its methods, we can
simulate the behavior of different car instances in a structured and object-oriented manner.
JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one
that calls the main method present in a Java code. JVM is a part of JRE(Java Runtime
Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer
can develop Java code on one system and expect it to run on any other Java-enabled system
without any adjustment. This is all possible because of JVM.
When we compile a .java file, .class files(contains byte-code) with the same class names
present in .java file are generated by the Java compiler. This .class file goes into various steps
when we run it. These steps together describe the whole JVM.
● Loading
● Linking
● Initialization
Loading:
The Class loader reads the “. class” file, generate the corresponding binary data and save it in
the method area. For each “ .class” file, JVM stores the following information in the method
area.
● The fully qualified name of the loaded class and its immediate parent class.
● Whether the “ .class” file is related to Class or Interface or Enum.
● Modifier, Variables and Method information etc.
After loading the “ .class” file, JVM creates an object of type Class to represent this file in
the heap memory. Please note that this object is of type Class predefined in java.lang
package. These Class object can be used by the programmer for getting class level
information like the name of the class, parent name, methods and variable information etc. To
get this object reference we can use getClass() method of Object class.
Java// A Java program to demonstrate working // of a Class type object created by JVM // to
represent .class file in memory. import java.lang.reflect.Field; import
java.lang.reflect.Method; // Java code to demonstrate use // of Class object created by JVM
public class Test { public static void main(String[] args) { Student s1 = new Student(); //
Getting hold of Class // object created by JVM. Class c1 = s1.getClass(); // Printing type of
object using c1. System.out.println(c1.getName()); // getting all methods in an array Method
m[] = c1.getDeclaredMethods(); for (Method method : m)
System.out.println(method.getName()); // getting all fields in an array Field f[] =
c1.getDeclaredFields(); for (Field field : f) System.out.println(field.getName()); } } // A
sample class whose information // is fetched above using its Class object. class Student {
private String name; private int roll_No; public String getName() { return name; } public
void setName(String name) { this.name = name; } public int getRoll_no() { return roll_No; }
public void setRoll_no(int roll_no) { this.roll_No = roll_no; } }
Output
Note: For every loaded “ .class” file, only one object of the class is created.
Student s2 = new Student(); // c2 will point to same object where // c1 is pointing Class c2 =
s2.getClass(); System.out.println(c1==c2); // true
Linking
● Verification: It ensures the correctness of the .class file i.e. it checks whether this file
is properly formatted and generated by a valid compiler or not. If verification fails, we
get run-time exception java.lang.VerifyError. This activity is done by the component
ByteCodeVerifier. Once this activity is completed then the class file is ready for
compilation.
● Preparation: JVM allocates memory for class static variables and initializing the
memory to default values.
● Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.
Initialization
In this phase, all static variables are assigned with their values defined in the code and static
block(if any). This is executed from top to bottom in a class and from parent to child in the
class hierarchy. In general, there are three class loaders:
● Bootstrap class loader: Every JVM implementation must have a bootstrap class
loader, capable of loading trusted classes. It loads core java API classes present in
the “JAVA_HOME/lib” directory. This path is popularly known as the bootstrap path.
It is implemented in native languages like C, C++.
● Extension class loader: It is a child of the bootstrap class loader. It loads the classes
present in the extensions directories “ JAVA_HOME/jre/lib/ext”(Extension path) or
any other directory specified by the java.ext.dirs system property. It is implemented in
java by the sun.misc.Launcher$ExtClassLoader class.
● System/Application class loader: It is a child of the extension class loader. It is
responsible to load classes from the application classpath. It internally uses
Environment Variable which mapped to java.class.path. It is also implemented in Java
by the sun.misc.Launcher$AppClassLoader class.
Java// Java code to demonstrate Class Loader subsystem public class Test { public static void
main(String[] args) { // String class is loaded by bootstrap loader, and // bootstrap loader is
not Java object, hence null System.out.println(String.class.getClassLoader()); // Test class is
loaded by Application loader System.out.println(Test.class.getClassLoader()); } }
Output
null jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f
Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader
delegate load request to extension class loader and extension class loader delegate request to
the bootstrap class loader. If a class found in the boot-strap path, the class is loaded otherwise
request again transfers to the extension class loader and then to the system class loader. At
last, if the system class loader fails to load class, then we get run-time exception
java.lang.ClassNotFoundException.
2. Class Loaders
● Bootstrap Class Loader: Loads core Java API classes from the JAVA_HOME/lib
directory. It is implemented in native code and is not a Java object.
● Extension Class Loader: Loads classes from the JAVA_HOME/jre/lib/ext directory
or any directory specified by the java.ext.dirs system property. It is implemented in
Java.
● System/Application Class Loader: Loads classes from the application classpath,
which is specified by the java.class.path environment variable. It is also implemented
in Java.
Example:
● Method area: In the method area, all class level information like class name,
immediate parent class name, methods and variables information etc. are stored,
including static variables. There is only one method area per JVM, and it is a shared
resource.
● Heap area: Information of all objects is stored in the heap area. There is also one
Heap Area per JVM. It is also a shared resource.
● Stack area: For every thread, JVM creates one run-time stack which is stored here.
Every block of this stack is called activation record/stack frame which stores methods
calls. All local variables of that method are stored in their corresponding frame. After
a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared
resource.
● PC Registers: Store address of current execution instruction of a thread. Obviously,
each thread has separate PC Registers.
● Native method stacks: For every thread, a separate native stack is created. It stores
native method information.
4. Execution Engine
Execution engine executes the “ .class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions. It can be
classified into three parts:
● Interpreter: It interprets the bytecode line by line and then executes. The disadvantage
here is that when one method is called multiple times, every time interpretation is
required.
● Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so
re-interpretation is not required, thus efficiency is improved.
● Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector,
refer Garbage Collector.
It is an interface that interacts with the Native Method Libraries and provides the native
libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be
called by C/C++ libraries which may be specific to hardware.
These are collections of native libraries required for executing native methods. They include
libraries written in languages like C and C++.