Basics of Java
Basics of Java
A class is a user defined data type which groups the data member and Student s1 = new Student(); // Creating an object
its associated functions together.
s1.name = "John";
Naming Convention Pascal Case ie (FileReader)
s1.age = 20;
It is a logical representation and does not occupy memory until an object
s1.study(); // Output: John is studying
is created.
}
It can contain:
}
o Fields (variables) – to store data.
public int getAge() { ✅ In simple terms: A single method or function can perform different
tasks depending on the object that calls it.
return age;
}
🔧 How Polymorphism Works in Java
Java achieves polymorphism in two primary ways:
public void setAge(int age) {
1. Compile-time Polymorphism (Static Binding)
if (age > 18) {
2. Runtime Polymorphism (Dynamic Binding)
this.age = age;
Let’s break these down:
} else {
1️Compile-time Polymorphism (Method Overloading)
System.out.println("Age must be greater than
18."); This type of polymorphism is resolved at compile time.
It is achieved through method overloading — defining multiple
} methods with the same name but different parameters in the same
class.
}
✅ Example:
}
class Calculator {
public class Main {
int add(int a, int b) {
public static void main(String[] args) {
return a + b;
Employee emp = new Employee();
}
emp.setName("John");
emp.setAge(25);
double add(double a, double b) {
return a + b;
System.out.println("Name: " + emp.getName());
}
System.out.println("Age: " + emp.getAge());
}
int add(int a, int b, int c) { void makeSound() {
return a + b + c; System.out.println("Cat meows");
} }
} }
Calculator calc = new Calculator(); Animal a;
System.out.println(calc.add(2, 3)); // Output: 5 a = new Dog();
System.out.println(calc.add(2.5, 3.5)); // Output: 6.0 a.makeSound(); // Output: Dog barks
System.out.println(calc.add(1, 2, 3)); // Output: 6 a = new Cat();
a.makeSound(); // Output: Cat meows
2️Runtime Polymorphism (Method Overriding) The method to call is decided at runtime, depending on the actual
object referred to by the parent class reference.
This type of polymorphism is resolved at runtime.
It is achieved through method overriding, where a subclass provides
its own version of a method already defined in the parent class.
🎯 Why is Polymorphism Important?
✅ Example:
Benefit Description
class Animal {
Code Same method name can be reused in
void makeSound() { Reusability different ways
System.out.println("Animal makes a sound");
Flexibility One interface, multiple implementations
}
Easy
Cleaner and modular code structure
} Maintenance
2. Subclass (Child Class)(Derived Class): Single inheritance allows one class to inherit from another.
o The class that inherits properties and methods from the Multilevel inheritance creates a chain of inheritance.
superclass.
Hierarchical inheritance allows multiple subclasses to inherit
3. extends Keyword: from the same superclass.
o Used to create a subclass in Java. The child class inherits Multiple inheritance is achieved using interfaces in Java to
the members (fields and methods) of the parent class. avoid ambiguity.
Feature Description }
Keyword interface }
Step 3: Use the Implementation
Abstract by default, can include default and static
Methods
methods (Java 8+), private methods (Java 9+) public class Main {
Variables public static final (constants only) public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Output: Dog barks }
d.sleep(); // Output: Animal sleeps @Override
Animal.sleep(); // Output: Animal sleeps protected void finalize() throws Throwable {
} System.out.println("Object is garbage collected!");
} }
📌 Why Use Interfaces? }
To achieve loose coupling 📌 Key Points
To implement multiple inheritance Automatic memory management
To define a contract for what a class should do Reduces risk of memory leaks
Garbage Collector Can’t predict when GC will run
Garbage Collection (GC) is a process by which the Java Virtual finalize() is deprecated in newer Java versions (use Cleaner or try-
Machine (JVM) automatically removes unused or unreferenced with-resources instead)
objects from memory to free up space and prevent memory leaks.
Lambda Expressions in Java
Lambda expressions in Java, introduced in Java 8, provide a concise way
🔧 Why Garbage Collection is Needed to represent functional interfaces (interfaces with a single abstract
method) in the form of an expression. They enable you to write more
Java handles memory allocation automatically. functional-style code and work seamlessly with streams.
When objects are no longer needed or cannot be reached, the
garbage collector cleans them up.
🧠 What is a Lambda Expression?
This ensures efficient memory management without requiring
manual free() calls (like in C/C++). A lambda expression is a function that can be passed around and
executed, and it helps to reduce boilerplate code (e.g., anonymous
classes). The general syntax is:
System.gc(); // Suggests JVM to run GC (parameters) -> expression
Example of GC in Action Syntax:
class Test { (parameters) -> {method-body}
public static void main(String[] args) { ✅ Lambda Expression Syntax Breakdown:
String str = new String("Hello"); 1. Parameters – Input parameters (can be a single or multiple).
str = null; // Now the "Hello" object is eligible for 2. Arrow (->) – Separates parameters from the body.
GC
System.gc(); // JVM may or may not run GC
3. Expression/Method Body – The logic that the lambda Greeting greeting = () -> System.out.println("Hello,
expression will perform. World!");
greeting.greet();
🧪 Example 1: Simple Lambda Expression }
Before Java 8 (Using Anonymous Class): }
interface Greeting { The lambda expression () -> System.out.println("Hello, World!")
replaces the anonymous class.
void greet();
📚 Lambda Expression Example with Parameters
}
Let's say you have a Calculator interface that performs a simple
operation:
public class Main { interface Calculator {
public static void main(String[] args) { int operation(int a, int b);
Greeting greeting = new Greeting() { }
@Override You can implement it with a lambda expression:
public void greet() { public class Main {
System.out.println("Hello, World!"); public static void main(String[] args) {
} // Addition
}; Calculator add = (a, b) -> a + b;
greeting.greet(); System.out.println("Addition: " + add.operation(5,
} 3)); // Output: 8
} // Multiplication