CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Key Reasons:
1. Platform Independent
Java code is compiled into bytecode, which runs on any device using the Java Virtual
Machine (JVM). This ensures "Write Once, Run Anywhere" (WORA) capability.
2. Object-Oriented Programming (OOP)
Java supports core OOP principles like inheritance, encapsulation, polymorphism, and
abstraction, which make code more modular, reusable, and maintainable.
3. Robust and Secure
Java provides strong memory management, exception handling, and type checking. It
also has built-in security features like bytecode verification and sandboxing.
4. Automatic Memory Management
Java has a Garbage Collector that automatically handles memory allocation and
deallocation, reducing the chances of memory leaks.
5. Rich Standard Library
Java offers a vast collection of pre-built classes and APIs (like java.util, java.io, java.net),
which simplify development tasks.
6. Multithreading Support
Java allows concurrent execution of multiple threads, making it suitable for applications
like games, web servers, and real-time systems.
7. Wide Community and Tools
Java has a large developer community, rich documentation, and strong IDE support
(e.g., Eclipse, IntelliJ), which help in faster development and learning.
8. Used in Various Domains
Java is used in developing desktop applications, web apps, Android apps, enterprise
systems, IoT, and cloud computing.
Conclusion:
Java is a powerful, versatile, and reliable programming language that balances performance,
security, and portability, making it ideal for modern software development across different
platforms.
History of Java
Java is a high-level, object-oriented programming language developed by James Gosling and
his team at Sun Microsystems in the early 1990s.
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Timeline of Java History:
1. 1991 – Project Start (Green Project):
Java began as a project called the Green Project, aimed at developing software for
embedded systems like televisions.
2. 1995 – Official Release:
The language was originally named Oak, but it was renamed Java (inspired by Java
coffee) due to trademark issues.
Java was officially launched by Sun Microsystems in 1995.
3. 1996 – Java 1.0:
The first official version, Java 1.0, was released with the slogan "Write Once, Run
Anywhere (WORA)".
4. 1998 – Java 2 (J2SE):
Java was rebranded into different editions like J2SE (Standard Edition), J2EE
(Enterprise Edition), and J2ME (Micro Edition).
5. 2006 – Open Source (OpenJDK):
Sun made Java’s source code open-source under the project OpenJDK.
6. 2010 – Oracle Acquisition:
Oracle Corporation acquired Sun Microsystems and took over Java’s development and
maintenance.
7. 2017 – New Release Model:
Oracle announced a 6-month release cycle for Java versions starting from Java 9.
Conclusion:
Java has evolved from a simple embedded system language to a powerful, general-purpose
programming platform. Its platform independence, security, and robustness have made it one
of the most popular programming languages in the world.
JVM & JRE
JVM (Java Virtual Machine):
• JVM is an abstract machine that executes Java bytecode.
• It is platform-dependent software used to run Java programs.
• It converts bytecode into machine code (interpreted or compiled using JIT).
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Responsibilities:
• Memory management (Heap, Stack)
• Garbage Collection
• Security and bytecode verification
• Multithreading support
JRE (Java Runtime Environment):
• JRE is a software package that provides everything needed to run Java applications.
• It includes:
o JVM
o Java class libraries (e.g., java.util, java.io)
o Other runtime components
Note:
• JRE = JVM + Libraries + Supporting files
• It does not contain the compiler (javac), so it can’t compile Java code.
Difference Between JVM and JRE:
Feature JVM JRE
Full Form Java Virtual Machine Java Runtime Environment
Role Executes bytecode Provides environment to run Java
Includes Only JVM JVM + Libraries
Developer Use For execution For end-users to run Java apps
✅ Java Environment
The Java Environment refers to the set of tools and components required to develop, compile,
run, and debug Java programs. It includes the following key parts:
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
1. JDK (Java Development Kit)
• It is the complete package for Java development.
• Includes:
o JRE (Java Runtime Environment)
o Development tools like javac, java, javadoc, jar
• Required by developers to write and compile Java code.
2. JRE (Java Runtime Environment)
• It is used to run Java programs.
• Includes:
o JVM (Java Virtual Machine)
o Core Java libraries
• Does not include compiler, so cannot be used for development.
3. JVM (Java Virtual Machine)
• It is the engine that runs Java bytecode.
• Converts .class bytecode into native machine code.
• Handles memory management, security, and thread management.
4. Java Compiler (javac)
• Converts .java source files into .class bytecode files.
5. Bytecode
• Intermediate code generated by compiler.
• Platform-independent and executed by the JVM.
Conclusion:
The Java Environment ensures platform independence and smooth execution of Java programs.
With JDK, JRE, and JVM working together, Java provides a robust development and runtime
platform.
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
✅ Java Source File Structure
A Java source file is a .java file that contains the code written in Java. It must follow a specific
structure to be valid and executable.
Basic Structure:
// 1. Package declaration (optional)
package mypackage;
// 2. Import statements (optional)
import java.util.Scanner;
// 3. Class declaration
public class MyClass {
// 4. Main method (entry point)
public static void main(String[] args) {
System.out.println("Hello, Java!");
// 5. Other methods or classes (optional)
void greet() {
System.out.println("Welcome!");
Explanation of Sections:
Section Description
package Declares the package (optional but must be at the top)
import Imports Java classes or packages
class Declares the main class (filename should match this name)
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Section Description
main() Entry point of Java program
Other methods/classes Additional logic or helper classes (optional)
Rules to Remember:
• File name must match the public class name.
Rule:
1. If the class is public →
✔ File name must match the public class name.
Otherwise, you’ll get a compile-time error.
2. If there is no public class →
✔ You can give any file name (but it should still have .java extension).
✔ The class can be default (non-public).
• Only one public class allowed per file.
• Code must be inside a class or interface.
Conclusion:
Understanding the structure helps in organizing code, avoiding errors, and writing standard Java
programs that are easy to compile and run.
✅ Compilation Fundamentals in Java
Compilation is the process of converting source code (.java) into bytecode (.class) that can
be executed by the Java Virtual Machine (JVM).
Steps in Java Compilation:
1. Writing Code
The developer writes Java code in a .java file.
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
2. Compiling Code
The code is compiled using the javac compiler:
nginx
Copy code
javac MyProgram.java
This generates a .class file containing bytecode.
3. Bytecode Generation
o Bytecode is a platform-independent intermediate code.
o It can run on any system with a JVM.
4. Execution by JVM
The JVM reads the .class file and either:
o Interprets bytecode line-by-line, or
o Uses JIT (Just-In-Time) compiler to convert it into machine code.
Tools Involved in Compilation:
Tool Purpose
javac Java compiler (compiles .java files)
JVM Runs the bytecode (.class)
JRE Provides runtime environment
Conclusion:
Compilation in Java ensures that code is converted into efficient and portable bytecode. This
two-step process (compile and execute) gives Java its platform independence and security.
✅ 1. Defining Classes in Java
A class is a blueprint for creating objects.
class Car {
String color;
int speed;
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
✅ 2. Constructors
A constructor initializes objects. It has the same name as the class and no return type.
class Car {
String color;
Car(String c) { // Constructor
color = c;
✅ 3. Methods
A method performs actions/operations.
class Car {
void drive() {
System.out.println("Car is driving");
✅ 4. Access Specifiers
Control visibility of class members.
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Modifier Access Level
public Accessible everywhere
private Accessible within the class
Accessible in same package and
protected
subclass
(default) Accessible within the package
public class Demo {
private int x = 10; // Only accessible in this class
🔹 What are Static Members?
In Java, static members (variables or methods) are associated with the class itself, not with
any specific object.
They are shared across all instances (objects) of the class.
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Types of Static Members:
Type Description
Static Variable Shared across all objects. Memory is allocated once.
Static Method Can be called without creating an object.
Static Block Runs only once when the class is first loaded.
Static Class A nested class marked as static.
Why Use Static Members?
• To save memory (only one copy exists)
• To call utility methods (like Math.pow())
• To access common data across all objects
class Student {
static String college = "ABC College"; // shared variable
String name;
int roll;
Student(String n, int r) {
name = n;
roll = r;
void display() {
System.out.println(roll + " " + name + " " + college);
public class Main {
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
public static void main(String[] args) {
Student s1 = new Student("Saurabh", 1);
Student s2 = new Student("Ankit", 2);
s1.display();
s2.display();
class MathTool {
static int count = 0; // Static variable
static void showCount() {
System.out.println(count);
🔹 What is final in Java?
The keyword final is a non-access modifier used to restrict modification.
It can be applied to:
1. Variables
2. Methods
3. Classes
1. Final Variables
A final variable cannot be reassigned after it is initialized.
➤ Syntax:
final int x = 10;
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
x = 20; // Error: cannot assign a value to final variable
2. Final Methods
A final method cannot be overridden by subclasses.
➤ Final Method Example:
java
Copy code
class Animal {
final void sound() {
System.out.println("Animal makes sound");
class Dog extends Animal {
// void sound() { } // Error: cannot override final method
3. Final Classes
A final class cannot be extended (no inheritance allowed).
➤ Final Class Example:
final class Vehicle {
void type() {
System.out.println("This is a vehicle");
// class Car extends Vehicle { } // Error: cannot inherit from final class
Use Case:
Use final class to prevent inheritance for security or design reasons (e.g., java.lang.String is
final).
Rules and Summary Table:
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Final Keyword Used On Meaning
Variable Cannot be reassigned
Method Cannot be overridden
Class Cannot be inherited
✅ 7. Comments
Used to explain code.
// This is a single-line comment
/*
This is a
multi-line comment
*/
✅ Data Types in Java
In Java, data types define the type of value a variable can hold. Java is strongly typed, which
means each variable must have a declared type.
Categories of Data Types:
1. Primitive Data Types
(Java provides 8 built-in primitive types)
Type Size Default Value Description Example
byte 1 byte 0 Small integers (–128 to 127) byte b = 100;
short 2 bytes 0 Medium integers short s = 500;
int 4 bytes 0 Default for integers int x = 1000;
long 8 bytes 0L Large integers long l = 1000000000L;
float 4 bytes 0.0f Decimal numbers (low precision) float f = 5.5f;
double 8 bytes 0.0d Decimal (high precision) double d = 10.1234;
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Type Size Default Value Description Example
char 2 bytes '\u0000' Single Unicode character char c = 'A';
boolean 1 bit false true or false boolean b = true;
2. Non-Primitive (Reference) Data Types
Used for objects, arrays, and classes.
Type Description Example
String Sequence of characters String s = "Java";
Array Collection of same-type values int[] arr = {1,2,3};
Class Blueprint for objects Car myCar = new Car();
Interface Contract-like behavior definition Runnable r = new Task();
Object Parent class of all Java objects Object o = new Object();
Code Example:
public class DataTypeExample {
public static void main(String[] args) {
// Primitive types
byte b = 100;
int num = 5000;
float pi = 3.14f;
char grade = 'A';
boolean passed = true;
// Reference types
String name = "Saurabh";
int[] marks = {90, 85, 95};
System.out.println("Byte: " + b);
System.out.println("Int: " + num);
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
System.out.println("Float: " + pi);
System.out.println("Char: " + grade);
System.out.println("Boolean: " + passed);
System.out.println("String: " + name);
System.out.println("Array element: " + marks[0]);
Output:
Byte: 100
Int: 5000
Float: 3.14
Char: A
Boolean: true
String: Saurabh
Array element: 90
Summary:
Primitive Types = Fixed size, faster, not objects
Non-Primitive Types = Objects, more powerful and flexible
✅ Variables in Java
Definition:
A variable in Java is a named memory location used to store data. The value stored in a
variable can change during program execution.
Syntax:
dataType variableName = value;
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Example:
int age = 20;
Types of Variables in Java:
Type Defined Inside Memory Scope Example
Temporary (method- int x = 10; inside a
Local Inside a method/block
level) method
Inside a class, outside methods (non- Each object has its
Instance int age; inside class
static) copy
Shared among all
Static Inside a class with static keyword static int count = 0;
objects
1. Local Variable Example:
public class Demo {
void show() {
int x = 5; // Local variable
System.out.println("x = " + x);
Output:
ini
Copy code
x=5
2. Instance Variable Example:
class Student {
String name; // Instance variable
void display() {
System.out.println("Name: " + name);
}
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Output (after assigning name in main):
makefile
Copy code
Name: Saurabh
3. Static Variable Example:
class Counter {
static int count = 0; // Static variable
Counter() {
count++;
System.out.println("Count: " + count);
Output:
makefile
Copy code
Count: 1
Count: 2
✅ Operators in Java
Definition:
Operators are special symbols used to perform operations on variables and values, such as
arithmetic, comparison, logical, etc.
Types of Operators in Java:
Operator Type Description
1. Arithmetic Operators Perform basic math operations
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Operator Type Description
2. Relational (Comparison) Compare two values
3. Logical Operators Combine boolean expressions
4. Assignment Operators Assign values
5. Unary Operators Work with a single operand
6. Bitwise Operators Perform bit-level operations
7. Ternary Operator Conditional expressions (? :)
1. Arithmetic Operators
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a * b
/ Division a/b
% Modulus a%b
int a = 10, b = 3;
System.out.println(a + b); // 13
2. Relational Operators
Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater or equal a >= b
<= Less or equal a <= b
3. Logical Operators
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Operator Meaning Example
&& Logical AND a > 5 && b < 10
` `
! Logical NOT !(a == b)
4. Assignment Operators
Operator Meaning Example
= Assign a=5
+= Add and assign a += 2;
-= Subtract and assign a -= 1;
*= Multiply and assign a *= 3;
/= Divide and assign a /= 2;
5. Unary Operators
Operator Meaning Example
+ Unary plus +a
- Unary minus -a
++ Increment a++ / ++a
-- Decrement a-- / --a
! Logical NOT !true
6. Bitwise Operators
Operator Meaning
& Bitwise AND
` `
^ Bitwise XOR
Bitwise
~
complement
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Operator Meaning
<< Left shift
>> Right shift
int a = 5; // 0101
int b = 3; // 0011
System.out.println(a & b); // 1
7. Ternary Operator
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Max = " + max);
Output:
ini
Copy code
Max = 20
✅ 1. Control Flow in Java
Definition:
Control flow statements control the execution path of a program based on conditions or
loops.
Types of Control Flow Statements:
Type Description
Conditional if, if-else, switch
Looping for, while, do-while
Branching break, continue, return
Examples:
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
a) If-Else:
int age = 18;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Not Adult");
b) Switch:
java
Copy code
int day = 2;
switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
default: System.out.println("Other Day");
c) For Loop:
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
Output:
Copy code
12345
✅ 2. Arrays in Java
Definition:
An array is a collection of elements of the same data type stored at contiguous memory
locations.
Types of Arrays:
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
• One-dimensional: int[] arr = new int[5];
• Two-dimensional: int[][] matrix = new int[2][3];
Example of 1D Array:
java
Copy code
int[] arr = {10, 20, 30};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
Output:
Copy code
10
20
30
Example of 2D Array:
java
Copy code
int[][] mat = {
{1, 2},
{3, 4}
};
System.out.println(mat[1][1]); // 4
Array Properties:
• Fixed size
• Random access
• Stored in heap memory
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
✅ 3. Strings in Java
Definition:
A String is a sequence of characters. In Java, it is an object of the String class in java.lang
package.
Creating Strings:
java
Copy code
String s1 = "Java"; // using literals
String s2 = new String("Java"); // using object
Common String Methods:
Method Description
length() Returns length of string
charAt(index) Returns character at index
equals() Checks equality
substring() Returns substring
toUpperCase() Converts to upper case
concat() Appends one string to another
Example:
java
Copy code
String name = "Saurabh";
System.out.println(name.length()); // 7
System.out.println(name.charAt(2)); // u
System.out.println(name.toUpperCase()); // SAURABH
System.out.println(name.substring(1, 4));// aur
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
String is Immutable:
You cannot change a string after it's created. Modifications result in a new object.
String Comparison:
• == → compares reference (memory)
• .equals() → compares content
✅ 1. Class in Java
Definition:
A class is a blueprint for creating objects. It defines variables and methods.
Syntax:
java
Copy code
class ClassName {
// fields (variables)
// methods
}
Example:
java
Copy code
class Student {
int id;
String name;
void display() {
System.out.println(id + " " + name);
}
}
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
✅ 2. Object in Java
Definition:
An object is an instance of a class. It has real existence in memory.
Creating an Object:
java
Copy code
Student s1 = new Student(); // Object creation
✅ 3. Inheritance in Java
Definition:
Inheritance allows a class to acquire properties and methods of another class. It
promotes code reuse.
Syntax:
java
class SubClass extends SuperClass { }
// Superclass
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
}
}
// Main class
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
}
}
✅ 4. Super Class and Sub Class
Term Description
Superclass The parent/base class (gives properties)
Subclass The child/derived class (inherits properties)
Example of Inheritance:
java
Copy code
// Superclass
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
// Subclass
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Using the Subclass:
java
Copy code
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
}
Output:
Animal eats
Dog barks
5. Method Overriding
Definition:
Overriding occurs when a subclass provides its own specific implementation of a
method already defined in the superclass.
Rules:
• Same method name, return type, and parameters.
• Must be in a subclass.
• Use @Override annotation (optional but recommended).
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Key Points:
• Runtime polymorphism
• Requires inheritance
• super keyword IS used to call parent method
• Subclass provides specific implementation
Example of Overriding:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Calls Dog’s overridden method
}
}
Output:
Dog barks
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
super.sound(); // Calls Animal's sound()
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
Summary Table:
Concept Meaning
Class Blueprint or template
Object Instance of a class
Acquiring properties from
Inheritance
parent class
Superclass Base/parent class
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Concept Meaning
Subclass Derived/child class
Redefining a superclass
Overriding
method
✅ What is Method Overloading?
Method Overloading means defining multiple methods with the same name but
different parameters (number, type, or order) in the same class.
It is a type of compile-time polymorphism.
Why use it?
To perform similar operations with different input types or different number of
inputs.
Rules for Method Overloading:
1. Methods must have the same name.
2. Must have different parameter list:
o Number of parameters
o Type of parameters
o Order of parameters
3. Return type may or may not be same.
4. Overloading happens in the same class.
Java Example:
class Calculator {
void add(int a, int b) {
System.out.println("Sum (int): " + (a + b));
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
void add(double a, double b) {
System.out.println("Sum (double): " + (a + b));
}
void add(int a, int b, int c) {
System.out.println("Sum of 3: " + (a + b + c));
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(2, 3);
calc.add(2.5, 4.5);
calc.add(1, 2, 3);
}
}
✅ What is Encapsulation?
Encapsulation is a concept of wrapping data (variables) and methods into a
single unit (class) and restricting direct access to data.
It is also known as Data Hiding.
Key Features of Encapsulation:
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Feature Description
Data hiding Fields are made private
Controlled access Through public getters and setters
Improves security Only safe values can be assigned
Reusability Easy to maintain and update
Java Example of Encapsulation:
class Student {
// private data members
private String name;
private int age;
// getter method
public String getName() {
return name;
}
// setter method
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
public void setAge(int age) {
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
if (age >= 0) this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Saurabh");
s.setAge(20);
System.out.println("Name: " + s.getName());
System.out.println("Age: " + s.getAge());
}
}
Why use Encapsulation?
• Prevents accidental changes to data
• Helps in debugging and modifying code
• Supports OOP principle of data hiding
✅ What is Polymorphism?
Polymorphism means "many forms".
In Java, it allows one interface or method to behave differently based on the context
(object type or parameters).
Types of Polymorphism:
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
Type Description Also Called
Compile-time Decided at compile time Method Overloading
Runtime Decided at runtime Method Overriding
1. Compile-Time Polymorphism (Method Overloading)
Example:
class Calculator {
void add(int a, int b) {
System.out.println("Sum: " + (a + b));
}
void add(double a, double b) {
System.out.println("Double Sum: " + (a + b));
}
}
2. Runtime Polymorphism (Method Overriding)
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
}
}
Why Polymorphism is Useful:
Benefit Description
Code Reusability Use same method with different logic
Flexibility Easily extend or override behavior
Readability Cleaner, more readable code
What is Abstraction?
Abstraction means hiding the internal implementation and showing only the
essential features to the user.
Example:
You use a mobile phone, but you don’t know how its internal circuits work.
Why Abstraction?
Benefit Description
Security Hides internal data
Simplicity Shows only required details
Flexibility Supports scalable and extendable design
How Abstraction is Achieved in Java?
Method Description
Abstract Class Can have abstract and non-abstract methods
Interface Fully abstract (Java 8+ allows default too)
1. Using Abstract Class
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
// Abstract class
abstract class Animal {
// Abstract method
abstract void sound();
// Non-abstract method
void eat() {
System.out.println("Animal eats food");
}
}
// Subclass
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Reference of abstract class
a.sound(); // Calls Dog's overridden method
a.eat(); // Calls Animal's method
}
}
What is an Interface?
An interface is a collection of abstract methods (methods without body).
In Java, interface is used to achieve 100% abstraction (until Java 7).
Interfaces can only contain method declarations (and constants).
From Java 8 onward, they can also have default and static methods with body.
Syntax:
interface InterfaceName {
void method1(); // implicitly public and abstract
}
Example: Abstraction using Interface
// Interface
interface Animal {
void sound(); // abstract method
// Implementing class
class Dog implements Animal {
CodeWithSubhsam CodeWithSubhsam
ὄ Click here to access the resource
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Interface reference
a.sound(); // Calls Dog's implementation
}
}