Object Oriented Programming
Object Oriented Programming
3. What is a Class?
class GfG {
public static void main(String args[])
{
Student student1 = new Student();
student1.name = "Rahul";
Consider a bank account system. In the real world, a bank account has sensitive
information like the account balance, account number, and personal details. To
manage this information securely, banks use encapsulation.
// Java Program to demonstrate Java Encapsulation
class Person {
// Driver Class
person.setName("John");
person.setAge(30);
7 - What is Abstraction?
Real-World Example: Driving a Car– When you drive a car, you interact with
the vehicle through its steering wheel, accelerator, brakes, and gear shift. You
don’t need to understand the complex mechanical and electronic systems inside
the car
- Abstract Class:
An abstract class is a class that cannot be instantiated directly. It can have both
abstract methods (methods without a body) and concrete methods (methods
with a body). An abstract class is typically used to provide a common base for
subclasses.
Abstract Method:
Example
abstract class Animal {
private String name;
// Abstracted class
class Dog extends Animal {
public Dog(String name) { super(name); }
myDog.makeSound();
myCat.makeSound();
} }
Output
Buddy barks
Fluffy meows
Explanation:
1. The Animal interface defines one abstract method sound() and one default
method eat().
2. The Dog class implements the Animal interface and provides an
implementation for the sound() method.
3. In the main method, we create an object of Dog and call both the sound()
(implemented in Dog) and eat() (inherited from the Animal interface)
methods.
Example: Example:
public abstract class Vehicle{ public interface Animal{
public abstract void drive() void speak();
} }
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
class One {
public void print_geek()
{ System.out.println("Geeks") ; } }
class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}
Output
Geeks
for
Geeks
class A {
public void print_A() { System.out.println("Class A"); } }
class B extends A {
public void print_B() { System.out.println("Class B"); } }
class C extends A {
public void print_C() { System.out.println("Class C"); } }
class D extends A {
public void print_D() { System.out.println("Class D"); } }
In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Please note that Java does not
support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C
is derived from interfaces A and B.
interface One {
public void print_geek();
}
interface Two {
public void print_for();
}
// Derived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output
Geeks
for
Geeks
Now, if Class D calls the display() method, the question arises: Should it use the
version from Class B or Class C? This creates ambiguity
If both B and C override a method from A, and D inherits from both, the compiler
can't decide which method to call.
In method overloading, multiple methods have the same name but different
parameter lists.
Example :
class Calculator {
class GFG {
Parent a;
a = new subclass1();
a.Print();
a = new subclass2();
a.Print(); }}
Output
subclass1
subclass2
Here in this program, When an object of a child class is created, then the
method inside the child class is called. This is because The method in the
parent class is overridden by the child class. Since The method is
overridden, This method has more priority than the parent method inside
the child class. So, the body inside the child class is executed.
Virtual functions-
It allows an object of a derived class to behave as if it were an object of the
base class. The derived class can override the virtual function of the base
class to provide its own implementation. The function call is resolved at
runtime, depending on the actual type of the object.
methods, or anything outside the scope of objects and classes. Since Java allows
class GFG {
}
Output
Default constructor
Example:
Java
import java.io.*;
class Geek {
String name;
int id;
this.name = name;
this.id = id; } }
class GFG {
} }
Output
GeekName :Avinash and GeekId :68
copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.
Note: In Java,there is no such inbuilt copy constructor available like in
other programming languages such as C++, instead we can create our
own copy constructor by passing the object of the same class to the other
instance(object) of the class.
Example:
Java
// Java Program for Copy Constructor
import java.io.*;
class Geek {
String name;
int id;
this.name = name;
this.id = id; }
Geek(Geek obj2) {
this.name = obj2.name;
this.id = obj2.id; } }
class GFG {
System.out.println("First Object");
}}
Output
First Object
Java Strings are immutable because once a String object is created, its value
cannot be changed. This design provides several benefits:
1. Security: Since Strings are used in sensitive operations (e.g., for storing
passwords, class names, or network connections), immutability prevents
accidental or malicious modifications.
Overall, immutability ensures that Java Strings are efficient, secure, and reliable.
1. StringBuilder
● Introduced in: Java 5.
● Thread Safety: Not thread-safe. If multiple threads access a
StringBuilder instance concurrently, and at least one thread
modifies it, you need to synchronise externally.
● Performance: Faster than StringBuffer because it does not have to
deal with thread synchronisation.
● Use Case: Use StringBuilder when you don't need synchronisation,
such as when only a single thread is modifying the content.
2. StringBuffer
Difference
16 . Interfaces in Java
Class Interface
17. ‘this’ reference in Java– this is a reference variable that refers to the
current object on which the method or constructor is being invoked. It can
be used to access instance variables and methods of the current object.
int a, int b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
void display()
{
System.out.println("a = " + a + " b = " + b); }
1. Overuse of this can make the code harder to read and understand.
2. Using this unnecessarily can add unnecessary overhead to the
program.
3. Using this in a static context results in a compile-time error.
4. Overall, this keyword is a useful tool for working with objects in Java,
but it should be used judiciously and only when necessary.
Static methods are the methods in Java that can be called without creating
an object of class. They are referenced by the class name itself or
reference to the Object of that class.
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can Private and final methods can’t be
be overloaded. overridden.
The super keyword in Java is used to refer to the immediate parent class
(superclass) of an object. It serves several important functions in the context of
inheritance, enabling interaction with the superclass's methods, constructors,
and instance variables.
void display() {
void display() {
void show() {
super.display(); }}
}}
25. final Keyword in Java
Eg - class Parent {
System.out.println("Final method"); } }
System.out.println("Child method"); }}
extend it.
// Class implementation
}
class SubClass extends FinalClass { // Compilation error, cannot extend final class
// Subclass implementation
26. The static keyword in Java is mainly used for memory management.
The static keyword in Java is used to share the same variable or method of
a given class. The users can apply static keywords with variables,
methods, blocks, and nested classes. The static keyword belongs to the
class rather than an instance of the class. The static keyword is used for a
class.
class Test
{ static int a = 10;
static int b;
static {
System.out.println("Static block initialized.");
b = a * 4; }
exception is thrown. The final block will be executed after the try
and catch blocks, but before control transfers back to its origin.
resource de-allocation.
These packages consist of a large number of classes which are a part of Java
API.Some of the commonly used built-in packages are:
User-defined packages: These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name of
the package). Then create the MyClass inside the directory with the first
statement being the package names.
28. enum (short for enumeration)- In Java, enum is a special data type
that represents a collection of constants. Enums are useful when you have a
fixed set of values that represent predefined options or categories, such as
days of the week, directions, or status codes.
break;
break;
break;
Default: System.out.println("Midweek!");
Break; }}}
Set Interface
Map Interface
Map is a data structure that supports the key-value pair mapping for the
data. It is mainly used in item-frequency scenarios where items are stored
along with their frequencies.
1. HashTable class implements a hash table, which maps keys to
values. Any non-null object can be used as a key or as a value. To
successfully store and retrieve objects from a hash table, the objects
used as keys must implement the hashCode method and the equals
method.
2. HashMap uses a technique called Hashing. It provides the basic
implementation of the Map interface of Java. It stores the data in
(Key, Value) pairs. To access a value in a HashMap, we must know its
key.
3. LinkedHashMap is very similar to a HashSet because the primary
difference is that this uses a doubly linked list to store the data and
retains the ordering of the elements.
Queue Interface
or interrupted
User-Defined Exceptions
In Java, exceptions that are under Error and , Runtime exception classes are
unchecked exceptions.
2. catch in Java- The catch block is used to handle the uncertain condition
of a try block. A try block is always followed by a catch block, which
handles the exception that occurs in the associated try block.
3. throw in Java- The throw keyword is used to transfer control from the
try block to the catch block.
try {
// Attempting to divide by zero
int result = divide(num1, num2);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handling the exception
System.out.println("Caught an exception: " + e.getMessage());
} finally {
// This block will always execute
System.out.println("This is the finally block, which runs whether an exception
occurs or not.");
}
System.out.println("Program continues...");
}
}
Race Condition:
Critical Section:
What is API
In Java, file handling is done using classes from the java.io and java.nio
packages. These classes allow you to read from and write to files, handle
different file types, manage directories, and handle exceptions. Some commonly
used classes for file handling include File, FileReader, FileWriter,
BufferedReader, BufferedWriter, and Scanner.
1. Creating a File
2. Writing to a File
3. Reading from a File
4. Appending to a File
5. Deleting a File
Both Shallow Copy and Deep Copy are techniques used to copy an object in Java,
but they differ in how they handle references to other objects inside the copied
object.
1. Shallow Copy:
● In a shallow copy, the fields of the original object are copied as it is.
● If the original object contains references to other objects (like arrays or other
class instances), only the references are copied, not the actual objects.
● As a result, both the original and copied objects share the same referenced
objects. If you modify the referenced objects through one copy, the changes
will be reflected in the other copy.
2. Deep Copy:
When we do a copy of some entity to create two or more than two entities
such that changes in one entity are not reflected in the other entities, then we
can say we have done a deep copy. In the deep copy, a new memory
allocation happens for the other entities, and reference is not copied to the
other entities. Each entity has its own independent reference.
Cloned object and the original Cloned object and the original
object are not disjoint. object are disjoint.