0% found this document useful (0 votes)
7 views

Basics of Java

The document provides an overview of Java's object-oriented programming concepts, including classes, objects, abstraction, encapsulation, polymorphism, and inheritance. It explains how classes serve as blueprints for objects, the importance of data hiding through encapsulation, and the different types of inheritance supported by Java. Additionally, it covers the use of abstract classes and interfaces for achieving abstraction and multiple inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Basics of Java

The document provides an overview of Java's object-oriented programming concepts, including classes, objects, abstraction, encapsulation, polymorphism, and inheritance. It explains how classes serve as blueprints for objects, the importance of data hiding through encapsulation, and the different types of inheritance supported by Java. Additionally, it covers the use of abstract classes and interfaces for achieving abstraction and multiple inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Basics of Java An object is an instance of a class.

1.1 Class and objects When a class is defined, no memory is allocated.


1.3 Abstraction, polymorphism inheritance, and encapsulation, Only when an object is created using the new keyword, memory is
allocated.
1.4 Abstract Class, Interface
Each object has:
1.4 Garbage Collector
 Its own copy of class variables.
1.5 Lambda expression
 Can access class methods.
Class:
public class Main {
A class is a blueprint or template that defines the structure and
behavior (data and methods) that objects of that type will have. public static void main(String[] args) {

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.

o Methods (functions) – to define behavior. What is Abstraction?


class Student { Abstraction is one of the four pillars of Object-Oriented
Programming (OOP).
String name; It is the process of hiding the implementation details and showing
only the essential features of an object.
int age;
✅ Key Idea:
void study() {
"Focus on what an object does, not how it does it."
System.out.println(name + " is studying");
✅ Why Abstraction?
}
 Reduces complexity
}
 Increases code reusability
In this example, Student is a class that has two attributes (name, age)
and one method (study()).  Improves maintainability and security
 Makes application easier to scale and extend

Object: How Abstraction is Achieved in Java?


Java provides two ways to achieve abstraction: Encapsulation is one of the core concepts of Object-Oriented
Programming (OOP).
It refers to binding the data (variables) and code (methods) that
Feature Description
manipulate the data into a single unit (class) and restricting direct
Abstract Can have abstract (incomplete) and (Non Abstract) access to some of the object's components.
Class methods
All methods are implicitly abstract (Java 7), or can include ✅ In simple terms: Encapsulation is about data hiding and protection.
Interface
default/static methods (Java 8+)
🎯 Key Goals of Encapsulation:
 Hide internal state of objects
abstract class Animal {
 Control access using getter/setter methods
abstract void makeSound(); // Abstract method
 Protect data from unauthorized access and modification
 Improve modularity and maintainability
void eat() {
System.out.println("This animal eats food.");
🧱 How to Implement Encapsulation in Java?
}
To achieve encapsulation:
}
1. Make the data members (fields) private
2. Provide public getter and setter methods to access and
class Dog extends Animal { update their values
void makeSound() {
System.out.println("Dog barks"); ✅ Example of Encapsulation:
} class Employee {
} // Step 1: Private data members
public class Main { private String name;
public static void main(String[] args) { private int age;
Animal a = new Dog();
a.makeSound(); // Dog barks // Step 2: Public getter and setter methods
a.eat(); // This animal eats food. public String getName() {
} return name;
} }
Encapsulation:
public void setName(String name) { }
// Add validation if needed What is Polymorphism in Java?
this.name = name; 📌 Definition:
} Polymorphism allows an object to take multiple forms or behave
differently based on the context in which it is used.

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

Easy to extend without changing existing


Scalability
code
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks"); Inheritance
} Inheritance is one of the four fundamental concepts of Object-Oriented
Programming (OOP).
}
It allows a class to inherit the fields (properties) and methods
(behaviors) from another class.
class Cat extends Animal {
By using inheritance, a new class can be created from an existing class, System.out.println("This animal eats food");
inheriting the functionality of the base class and adding or modifying
certain features. }
}

Types of Inheritance in Java:


1. Single Inheritance class Dog extends Animal {
In this type, a class inherits from only one superclass. This is the void bark() {
most basic form of inheritance.
System.out.println("The dog barks");
Example:
}
class Animal {
}
void eat() {
System.out.println("This animal eats food");
class Puppy extends Dog {
}
void play() {
}
System.out.println("The puppy plays");
class Dog extends Animal {
}
void bark() {
}
System.out.println("The dog barks");
Explanation:
}
 Puppy inherits from Dog, and Dog inherits from Animal.
}
 Puppy can access methods from both Dog and Animal.
Explanation:
3. Hierarchical Inheritance
 The class Dog inherits from the Animal class. In this type, multiple classes inherit from a single base class. All the
 Dog can access the method eat() from Animal. child classes can access the properties and methods of the same
parent class.
2. Multilevel Inheritance
In multilevel inheritance, a class is derived from another class, which Example:
in turn is derived from another class. This creates a chain of class Animal {
inheritance.
void eat() {
Example:
System.out.println("This animal eats food");
class Animal {
}
void eat() {
}
class Dog implements Animal, Pet {
class Dog extends Animal { public void eat() {
void bark() { System.out.println("The dog eats food");
System.out.println("The dog barks"); }
}
} public void play() {
System.out.println("The dog plays fetch");
class Cat extends Animal { }
void meow() { }
System.out.println("The cat meows"); Explanation:
}  Dog implements both Animal and Pet interfaces.
}  Dog provides its own implementations of eat() and play().
Explanation: 5. Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of
 Both Dog and Cat inherit from Animal. inheritance (usually single and multiple inheritance). While Java
 Both Dog and Cat can access the eat() method of Animal. doesn't support hybrid inheritance directly with classes, you can
simulate it using interfaces.
4. Multiple Inheritance (Through Interfaces)
Java does not support multiple inheritance using classes to avoid Example:
ambiguity. However, it supports multiple inheritance through interface Animal {
interfaces. A class can implement multiple interfaces.
void eat();
Example:
}
interface Animal {
void eat();
interface Pet {
}
void play();
}
interface Pet {
void play();
class Dog extends Animal implements Pet {
}
public void eat() {
System.out.println("The dog eats food"); 6. Constructor Inheritance:
} o Constructors are not inherited by the subclass. However,
the subclass can call the parent class constructor using
the super() keyword.
public void play() {
System.out.println("The dog plays fetch"); Advantages of Inheritance:
} 1. Code Reusability: Inheritance allows the reuse of code already
} written in the parent class, thus reducing redundancy.

o Explanation: 2. Maintainability: Modifying or fixing a bug in the parent class


will propagate to all its subclasses automatically.
 Dog extends Animal (single inheritance) and implements Pet
(multiple inheritance through interfaces). 3. Extensibility: New functionality can be added to existing classes
without modifying them, simply by creating new subclasses.
4. Organized Structure: Inheritance helps in creating a clear
Important Concepts in Inheritance: hierarchy in classes, making the code more organized and
modular.
1. Superclass (Parent Class)(Base class):
o The class from which properties and methods are
inherited. Key Points:

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.

4. super Keyword:  Constructor inheritance is not supported, but constructors of


the parent class can be called using the super keyword.
o Refers to the immediate parent class. It is used to access
parent class constructors, methods, and fields. Abstract Class
5. Method Overriding: An abstract class in Java is a class that cannot be instantiated
on its own and is meant to be extended by other classes. It can
o When a subclass provides a specific implementation for a have both abstract methods (without implementation) and non-
method that is already defined in its parent class. abstract methods (with implementation). It serves as a blueprint
o Overriding is used to change or extend the behavior of an for subclasses.
inherited method. ✅ Key Features of Abstract Class:
1. Declared using the abstract keyword. // Implement the abstract method
2. Can contain abstract methods (without body). @Override
3. Can contain concrete methods (with body). double calculateArea() {
4. Cannot be instantiated. return Math.PI * radius * radius;
5. Can have constructors, fields, and methods (like a normal class). }
6. Subclasses must implement all abstract methods unless the }
subclass is also abstract.
When to Use Abstract Class?
// Main class to test
 When you want to provide common functionality to multiple
subclasses but still enforce the implementation of certain public class Main {
methods in each subclass. public static void main(String[] args) {
 When there is a common base but objects should be created only Circle c = new Circle(7.0); // Creating a Circle
from the derived classes. object
// Abstract class double area = c.calculateArea();
abstract class Shape { System.out.println("Area of Circle: " + area);
// Abstract method }
abstract double calculateArea(); }
}
Feature /
Class Abstract Class Interface
Aspect

// Concrete subclass Blueprint to Incomplete class


Pure abstraction –
Definition create meant to be
class Circle extends Shape { defines a contract
objects extended
double radius;
No (can’t
Object No (can’t instantiate
Yes instantiate
Creation directly)
directly)
// Constructor
Non Abstract + Non Only abstract methods
Circle(double radius) { Method Types Abstract(wit Abstract (Java 7), can include
h body) methods default/static (Java 8+)
this.radius = radius;
} Can have Can have any Only public static final
Variables
any type type (constants)

Constructors Yes Yes No


Feature / Feature Description
Class Abstract Class Interface
Aspect
Implementatio
Class uses implements to implement an interface
n

All (private, Multiple


Access All (including All members are public A class can implement multiple interfaces
protected, Inheritance
Modifiers private) by default
etc.)
No
Interfaces can't be instantiated directly
Single Single Multiple inheritance Constructors
Inheritance
inheritance inheritance supported

Keyword Used class abstract class interface 🧪 Example


For creating When common Step 1: Define the Interface
To define a contract or
When to Use real objects base behavior is
capability
and behavior needed interface Animal {

Can be void makeSound(); // abstract method


Implements / extended by Extended by Implemented by
Extends other subclasses classes
classes default void sleep() {
System.out.println("Animal sleeps");

What is an Interface in Java? }

An interface in Java is a reference type, similar to a class, that can only }


contain abstract methods (until Java 7), and default/static Step 2: Implement the Interface
methods (from Java 8). Interfaces are used to achieve 100%
abstraction and multiple inheritance. class Dog implements Animal {
public void makeSound() {
✅ Key Features of Interfaces System.out.println("Dog barks");

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

After Java 8 (Using Lambda Expression): Calculator multiply = (a, b) -> a * b;

interface Greeting { System.out.println("Multiplication: " +


multiply.operation(5, 3)); // Output: 15
void greet();
}
}
}
public class Main {
Here, the lambda expression (a, b) -> a + b performs the addition
public static void main(String[] args) { operation.
🔧 Important Points about Lambda Expressions
1. Functional Interface: A lambda expression is used to provide // Create an ArrayList to store names
the implementation of the abstract method of a functional
interface. ArrayList<String> names = new ArrayList<>();

A functional interface is an interface with just one abstract names.add("John");


method. names.add("Alice");
2. No new keyword: You don't need the new keyword to names.add("Bob");
instantiate the interface implementation.
names.add("David");
3. Readability: Lambda expressions are more concise and
readable than anonymous class implementations. // Sort in ascending order
4. Parameters: If there is only one parameter, you can omit the Collections.sort(names, (a, b) -> a.compareTo(b));
parentheses:
// Sort in descending order
(x) -> x * 2 // Single parameter, no need for parentheses
Collections.sort(names, (a, b) -> b.compareTo(a));
If there are no parameters, you must use empty parentheses:
// Print the sorted list
() -> System.out.println("Hello");
System.out.println("Sorted Alphabetically: " +
🎯 Why Use Lambda Expressions? names);
1. Less Boilerplate Code: They remove the need for verbose }
anonymous class implementations.
}
2. Functional Programming: Enables you to use functional
programming concepts like map, filter, and reduce with public class PrimeNumberUsingLambda {
ease.
public static void main(String[] args) {
3. Improved Readability: Lambda expressions can make your
PrimeNumber primeChecker = (n) -> {
code more compact and easier to read.
if (n <= 1) return false;
🌍 Real-World Use Cases of Lambda Expressions
for (int i = 2; i <= Math.sqrt(n); i++) {
Event Listeners ,Processing Collections with
Streams ,Concurrency,Sorting. if (n % i == 0) return false;
Imp : }
import java.util.ArrayList; return true;
import java.util.Collections; };
System.out.println("Is 7 prime?
"primeChecker.isPrime(7));
public class Main {
}
public static void main(String[] args) {
}
interface PrimeNumber {
boolean isPrime(int n);
}

You might also like