OOPs unit-1 Notes
OOPs unit-1 Notes
UNIT -1
Object-oriented programming:
An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system.
For Example, Pen is an object. Its name is Reynolds; color is white, known as
its state. It is used to write, so writing is its behavior.
Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object
name, and use the keyword new:
Example:
int x = 5;
System.out.println(myObject.x);
}
Multiple Objects
Example:
int x = 5;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
There are four ways to create objects in Java. Strictly speaking, there is
only one way(by using a new keyword), and the rest internally use
a new keyword.
clone() method is present in the Object class. It creates and returns a copy
of the object.
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();
4. Deserialization
Example:
Test test = new Test();
test = new Test();
In the inheritance system, we use a parent class reference variable to store
a sub-class object. In this case, we can switch into different subclass
objects using the same referenced variable.
Example:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class Test
{
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}
btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
1. By reference variable
2. By method
3. By constructor
Java Classes
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
1. class <class_name>{
2. field;
3. method;
4. }
Method in Java
Advantage of Method
o Code Reusability AND Code Optimization
o new keyword in Java
o The new keyword is used to allocate memory at runtime. All objects
get memory in Heap memory area.
Abstraction
Abstract class in Java
Before learning the Java abstract class, let's understand the abstraction in
Java first.
Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you type the text and
send the message. You don't know the internal processing about the
message delivery.
Abstraction lets you focus on what the object does instead of how it does
it.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change
the body of the method.
In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.
In this example, if you create the instance of Rectangle class, draw() method
of Rectangle class will be invoked.
File: TestAbstraction1.java
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Output:I am a
I am b
I am c
I am d
Encapsulation
We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter methods to
set and get the data in it.
You learned from the previous chapter that private variables can only be
accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide
public get and set methods.
The get method returns the variable value, and the set method sets the
value.
Syntax for both is that they start with either get or set, followed by the
name of the variable, with the first letter in upper case:
Example
// Getter
return name;
// Setter
this.name = newName;
}
Example explained
Example
System.out.println(myObj.name); // error
John
Inheritance
The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.
Inheritance Example
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Polymorphism in Java
Upcasting
If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
1. interface I{}
2. class A{}
3. class B extends A implements I{}
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A
Object.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. } }
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading
When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can
be overloaded by changes in the number of arguments or/and a change in
the type of arguments.
Example 1:
Java
// Class 1
// Helper class
class Helper {
return a * b;
// Method 2
return a * b;
// Class 2
// Main class
class GFG {
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
Output
8
34.65
A list of the most important features of the Java language is given below.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:
Object-oriented
Platform Independent
ava is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language. A platform is the hardware or
software environment in which a program runs.
The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on top of other hardware-based
platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime
Environment (JRE) which is used to load Java classes into the Java
Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that
can violate access rights to objects.
o Security Manager: It determines what resources a class can access
such as reading and writing to the local disk.
Robust
o Architecture-neutral
o Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
o In C programming, int data type occupies 2 bytes of memory for 32-
bit architecture and 4 bytes of memory for 64-bit architecture.
However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
Distributed
Multi-threaded
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++.
What is JRE?
Java Run-time Environment (JRE) is the part of the Java Development Kit
(JDK). It is a freely available software distribution which has Java Class
Library, specific tools, and a stand-alone JVM. It is the most common
environment available on devices to run java programs. The source Java
code gets compiled and converted to Java bytecode. If you wish to run this
bytecode on any platform, you require JRE. The JRE loads classes, verify
access to memory, and retrieves the system resources. JRE acts as a layer on
the top of the operating system.
It also includes:
o Technologies which get used for deployment such as Java Web Start.
o Toolkits for user interface like Java 2D.
o Integration libraries like Java Database Connectivity
(JDBC) and Java Naming and Directory Interface (JNDI).
o Libraries such as Lang and util.
o Other base libraries like Java Management Extensions (JMX), Java
Native Interface (JNI) and Java for XML Processing (JAX-WS).
JRE has an instance of JVM with it, library classes and development tools. To
understand the working of JRE let us see an example of a simple "Hello
World" program.
1. import java.util.*
2. public static void main(String[] args){
3. System.out.println(?Hello world?);
4. }
Once you write this program, you have to save it with .java extension.
Compile your program. The output of the Java compiler is a byte-code
which is platform independent. After compiling, the compiler generates a
.class file which has the bytecode. The bytecode is platform independent
and runs on any device having the JRE. From here, the work of JRE begins.
To run any Java program, you need JRE. The flow of the bytecode to run is
as follows:
The following steps take place at runtime:
o Class Loader
At this step, the class loader loads various classes which are essential
for running the program. The class loader dynamically loads the
classes in the Java Virtual Machine.
When the JVM is started, three class loaders are used:
1. Bootstrap class loader
2. Extensions class loader
3. System class loader
o Byte code verifier
Byte code verifier can be considered as a gatekeeper. It verifies the
bytecode so that the code doesn't make any sort of disturbance for
the interpreter. The code is allowed to be interpreted only when it
passes the tests of the Bytecode verifier which checks the format and
checks for illegal code.
o Interpreter
Once the classes get loaded and the code gets verified, then
interpreter reads the assembly code line by line and does the
following two functions:
o Execute the Byte Code
o Make appropriate calls to the underlying hardware
To develop or run Java applications, you need to download and install the
Java SE Development Kit.
Step 1.) Download the Java SE latest release from the official site of the
oracle.
Step 2.) After downloading the file, you will have an executable file
downloaded. Run that file and keep everything as default and keep clicking
next and then install.
Step 3.) After completing the installation, your JDK and JRE would be
downloaded in the program files folder.
Step 4.) After complete installation, you need to set up the environment
variables.
Step 5.) Go to control panel -> System and Security -> System ->
Advanced System Settings. The following dialog box will appear.
Step 7.) Now add the path of your bin file present in the JRE file to the Path
variable.
Difference between JVM, JDK, and JRE
o JVM - Java Virtual Machine is a virtual machine which runs programs
which are compiled to bytecodes. The JVM is detailed by a
specification that formally describes what is required in a JVM
implementation. Having a specification ensures interoperability of
Java programs across different implementations so that program
authors using the Java Development Kit (JDK) need not worry about
traits of the underlying hardware platform.
o JDK- JDK is a wrapper around the JRE and additionally contains the
compiler, interpreter, debugger and other tools. It provides users with
features to run as well as develop Java programs.
o JRE- JRE is made up of class libraries, JVM and supporting files
Principle 1: Compilation
First, the source ‘.java’ file is passed through the compiler, which then
encodes the source code into a machine-independent encoding, known as
Bytecode. The content of each class contained in the source file is stored in
a separate ‘.class’ file. While converting the source code into the bytecode,
the compiler follows the following steps:
Step 1: Parse: Reads a set of *.java source files and maps the resulting
token sequence into AST (Abstract Syntax Tree)-Nodes.
Step 2: Enter: Enters symbols for the definitions into the symbol table.
Step 3: Process annotations: If Requested, processes annotations found
in the specified compilation units.
Step 4: Attribute: Attributes the Syntax trees. This step includes name
resolution, type checking and constant folding.
Step 5: Flow: Performs dataflow analysis on the trees from the previous
step. This includes checks for assignments and reachability.
Step 6: Desugar: Rewrites the AST and translates away some syntactic
sugar.
Step 7: Generate: Generates ‘.Class’ files.
The class files generated by the compiler are independent of the machine
or the OS, which allows them to be run on any system. To run, the main
class file (the class that contains the method main) is passed to the JVM
and then goes through three main stages before the final machine code is
executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
Let us discuss all 3 stages.
Stage 1: Class Loader
The main class is loaded into the memory bypassing its ‘.class’ file to the
JVM, through invoking the latter. All the other classes referenced in the
program are loaded through the class loader.
A class loader, itself an object, creates a flat namespace of class bodies
that are referenced by a string name. The method definition is provided
below illustration as follows:
Illustration:
// loadClass function prototype
Control Structures:
int x = 10;
if (x > 0) {
System.out.println("Positive");
} else {
System.out.println("Negative or zero");
Loops:
for loop: Executes a block of code a fixed number of times. for (int i = 0; i <
5; i++) {
int i = 0;
while (i < 5) {
i++;
do-while loop: Similar to the while loop but executes the block of code at
least once before checking the condition.
int i = 0;
do {
i++;
Methods: Methods are blocks of code that perform a specific task and are
reusable.
return a + b;
class Person {
String name;
int age;
}
Packages: Packages are used to organize classes and interfaces into
namespaces.
package com.example.myproject;
class Car {
speed++;
Constructors
String color;
int speed;
speed = 0;
Methods
class Car {
String color;
int speed;
return speed;
myCar.accelerate(20);
Access Specifiers
Static Members
return a + b;
Comments
// Single-line comment
/*
Multi-line comment
*/
Data Types
These are predefined data types provided by Java itself. They are simple,
efficient, and represent basic values. Here's a breakdown of the primitive
data types:
Data Size
Description Range
Type (bits)
Represents small whole
byte 8 -128 to 127
numbers
Represents whole numbers
short 16 -32,768 to 32,767
(slightly larger than byte)
Represents whole numbers -2,147,483,648 to
int 32
(most commonly used) 2,147,483,647
Represents large whole
long 64 -2^63 to (2^63) - 1
numbers
Represents single-precision Larger range of decimal
float 32
floating-point numbers numbers (approximate)
Represents double-
Even larger range of decimal
double precision floating-point 64
numbers (more precise)
numbers
Represents a single '\u0000' to '\uffff' (includes
char 16
character (uses Unicode) symbols)
Represents logical values
boolean 1 true or false
(true or false)
Example:
byte age = 25; // Stores a whole number between -128 and 127
Consider the range of values you need to store (e.g., use byte for
small numbers, int for most whole numbers).
Think about memory efficiency if dealing with large datasets (byte
and short use less memory than int).
For decimal numbers, choose between float (less precise but uses less
memory) and double (more precise but uses more memory).
Use boolean for true/false decisions.
Variables
Operators
Control Flow
int x = 10;
if (x > 5) {
} else {
Arrays
numbers[0] = 1;
numbers[1] = 2;
// ...
Types of Arrays