0% found this document useful (0 votes)
4 views17 pages

Module 2

The document provides comprehensive notes on Java programming, covering key concepts such as classes, objects, constructors, encapsulation, inheritance, polymorphism, abstract classes, interfaces, and inner classes. It explains the creation and use of classes and objects, the importance of encapsulation and access modifiers, and various inheritance types, along with method overloading and overriding. Additionally, it discusses the differences between abstract classes and interfaces, as well as the functionality of nested classes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

Module 2

The document provides comprehensive notes on Java programming, covering key concepts such as classes, objects, constructors, encapsulation, inheritance, polymorphism, abstract classes, interfaces, and inner classes. It explains the creation and use of classes and objects, the importance of encapsulation and access modifiers, and various inheritance types, along with method overloading and overriding. Additionally, it discusses the differences between abstract classes and interfaces, as well as the functionality of nested classes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming Notes

Module 2

2.1 Classes, Objects, and Constructors

Classes and Objects

A class is a blueprint used to create objects. It denes variables and methods.


An object is an instance of a class. It contains actual data and can perform actions.

Declaring and Creating Objects

Object creation involves two steps:


ˆ Declaration
ˆ Instantiation using new
class Box {
double width, height, depth;
}

class Demo {
public static void main(String[] args) {
Box b = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 30;

[Link]([Link]);
}
}

Output:

10

Instance Variables and Methods

ˆ Instance variables store data


ˆ Methods dene behavior
ˆ Access using dot operator
class Box {
double width, height, depth;

double volume() {
return width * height * depth;

1
}
}

class Test {
public static void main(String[] args) {
Box b = new Box();
[Link] = 2;
[Link] = 3;
[Link] = 4;

[Link]([Link]());
}
}

Output:

24.0

Constructors

A constructor is used to initialize objects.


ˆ Same name as class
ˆ No return type
ˆ Called automatically
Parameterized Constructor

class Box {
double width, height, depth;

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}

double volume() {
return width * height * depth;
}
}

class Test {
public static void main(String[] args) {
Box b = new Box(2, 3, 4);
[Link]([Link]());
}
}

Output:

24.0

Constructor Overloading

Multiple constructors with dierent parameters.

2
class Box {
double width, height, depth;

Box() {
width = height = depth = 1;
}

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}
}

Using this() Constructor

Used to call another constructor in the same class.


class Box {
double width, height, depth;

Box() {
this(1,1,1);
}

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}
}

2.2 Encapsulation and Access Modiers

Encapsulation

Encapsulation is the process of combining data and methods into a single unit (class) and restricting
direct access to the data.
It provides data hiding and protects object integrity.

Data Hiding using Getters and Setters

Instance variables are declared as private and accessed using public methods.
ˆ Getter  returns value
ˆ Setter  modies value
class Student {
private int marks;

public void setMarks(int m) {


marks = m;
}

public int getMarks() {


return marks;

3
}
}

class Test {
public static void main(String[] args) {
Student s = new Student();
[Link](85);
[Link]([Link]());
}
}

Output:

85

Benets of Encapsulation

ˆ Data security
ˆ Controlled access
ˆ Better maintainability
ˆ Flexibility to change implementation
Access Modiers

Access modiers dene the visibility of variables and methods.


ˆ private
ˆ default (no modier)
ˆ protected
ˆ public
Types of Access Modiers

ˆ private: Accessible only within the same class


ˆ default: Accessible within the same package
ˆ protected: Same package + subclasses
ˆ public: Accessible everywhere
Example: Access Modiers

class Demo {
private int a = 10;
int b = 20; // default
protected int c = 30;
public int d = 40;

void show() {
[Link](a + " " + b + " " + c + " " + d);
}
}

4
class Test {
public static void main(String[] args) {
Demo obj = new Demo();
[Link]();
}
}

Output:

10 20 30 40

Access Modier Table

Modier Class Package Subclass World


private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

2.3 Inheritance and Superclasses

Introduction to Inheritance

Inheritance allows one class to acquire properties and methods of another class. It represents an
IS-A relationship.
ˆ Superclass  Parent class
ˆ Subclass  Child class
A subclass inherits all accessible members of its superclass but cannot access private members
directly.

Syntax of Inheritance

class Parent {
int x = 10;
}

class Child extends Parent {


void show() {
[Link](x);
}
}

Example: Basic Inheritance

class Animal {
void sound() {
[Link]("Animal sound");
}
}

class Dog extends Animal {

5
void bark() {
[Link]("Dog barks");
}
}

class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}

Output:

Animal sound
Dog barks

Types of Inheritance

ˆ Single Inheritance
ˆ Multilevel Inheritance
ˆ Hierarchical Inheritance
Note: Java does not support multiple inheritance using classes.

Example: Multilevel Inheritance

class A {
void showA() {
[Link]("Class A");
}
}

class B extends A {
void showB() {
[Link]("Class B");
}
}

class C extends B {
void showC() {
[Link]("Class C");
}
}

class Test {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
[Link]();
}
}

Output:

6
Class A
Class B
Class C

super Keyword

The super keyword refers to the immediate parent class.


ˆ Call superclass constructor
ˆ Access superclass variables
ˆ Call superclass methods
Using super to Call Constructor

class A {
A() {
[Link]("Constructor A");
}
}

class B extends A {
B() {
super();
[Link]("Constructor B");
}
}

class Test {
public static void main(String[] args) {
B obj = new B();
}
}

Output:

Constructor A
Constructor B

Using super to Access Variables

class Parent {
int x = 10;
}

class Child extends Parent {


int x = 20;

void show() {
[Link](super.x);
[Link](x);
}
}

class Test {
public static void main(String[] args) {
Child obj = new Child();

7
[Link]();
}
}

Output:

10
20

Constructor Execution Order

Constructors execute from superclass to subclass.


ˆ Parent constructor executes rst
ˆ Then child constructor executes
Object Class

All classes in Java inherit from the Object class.


ˆ Provides common methods like:
 toString()
 equals()
 clone()

2.4 Polymorphism

Introduction to Polymorphism

Polymorphism means "many forms". It allows one interface to be used for dierent implementations.
ˆ One method name  multiple behaviors
Types of polymorphism in Java:
ˆ Compile-time polymorphism (Method Overloading)
ˆ Runtime polymorphism (Method Overriding)
Compile-Time Polymorphism (Method Overloading)
Method Overloading

Method overloading occurs when multiple methods have the same name but dierent parameters.
ˆ Must dier in number or type of parameters
ˆ Return type alone is not enough
class Add {
int sum(int a, int b) {
return a + b;
}

int sum(int a, int b, int c) {


return a + b + c;

8
}
}

class Test {
public static void main(String[] args) {
Add obj = new Add();

[Link]([Link](2, 3));
[Link]([Link](2, 3, 4));
}
}

Output:

5
9

Runtime Polymorphism (Method Overriding)


Method Overriding

Method overriding occurs when a subclass provides its own implementation of a method already
dened in the superclass.
ˆ Same method name and parameters
ˆ Cannot reduce access level
class Animal {
void sound() {
[Link]("Animal sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}

Output:

Dog barks

Dynamic Method Dispatch

Dynamic method dispatch means method calls are resolved at runtime.


A superclass reference can refer to a subclass object.
class Animal {
void sound() {
[Link]("Animal sound");

9
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

class Test {
public static void main(String[] args) {
Animal obj = new Dog();
[Link]();
}
}

Output:

Dog barks

Important Points

ˆ Overloading  compile-time decision


ˆ Overriding  runtime decision
ˆ Final and static methods cannot be overridden
ˆ Use @Override for safety
2.5 Abstract Classes

Abstraction

Abstraction is the process of hiding implementation details and showing only essential features.
ˆ Focus on what an object does, not how it does it
Abstraction in Java is achieved using:
ˆ Abstract classes
ˆ Interfaces
Abstract Class

An abstract class is declared using the abstract keyword.


ˆ Cannot be instantiated
ˆ Used as a base class
Features of Abstract Class

ˆ Can contain abstract and concrete methods


ˆ Can have variables and constructors
ˆ Can have static and nal methods
10
ˆ Can have object references
Abstract Methods

An abstract method has no body and must be implemented by subclasses.


abstract void show();

ˆ If a class has an abstract method  it must be abstract


ˆ Subclass must implement all abstract methods
Example: Abstract Class

abstract class Shape {


abstract double area();
}

class Circle extends Shape {


double r = 5;

double area() {
return 3.14 * r * r;
}
}

class Test {
public static void main(String[] args) {
Shape s = new Circle();
[Link]([Link]());
}
}

Output:

78.5

Constructor in Abstract Class

Abstract classes can have constructors which are called when subclass objects are created.
abstract class A {
A() {
[Link]("Constructor A");
}
}

class B extends A {
B() {
[Link]("Constructor B");
}
}

class Test {
public static void main(String[] args) {
B obj = new B();
}
}

11
Output:

Constructor A
Constructor B

Important Points

ˆ Abstract class cannot be instantiated


ˆ Can contain both abstract and concrete methods
ˆ Subclass must implement abstract methods
ˆ Used to achieve partial abstraction
2.6 Interfaces

Interface Concept

An interface is a contract that denes what a class must do, without specifying how it does it.
ˆ Declared using interface keyword
ˆ Cannot be instantiated
ˆ Used to achieve full abstraction
Key Characteristics

ˆ Methods are public and abstract by default


ˆ Variables are public static final (constants)
ˆ Cannot create objects of interfaces
ˆ Reference variables can be used
Implementing an Interface

A class implements an interface using the implements keyword.


interface Shape {
void draw();
}

class Circle implements Shape {


public void draw() {
[Link]("Drawing Circle");
}
}

class Test {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}

12
Output:

Drawing Circle

ˆ Methods must be declared public


ˆ Otherwise compiler error occurs
Multiple Inheritance using Interfaces

Java allows multiple inheritance through interfaces.


interface A {
void showA();
}

interface B {
void showB();
}

class Demo implements A, B {


public void showA() {
[Link]("A");
}

public void showB() {


[Link]("B");
}
}

class Test {
public static void main(String[] args) {
Demo obj = new Demo();
[Link]();
[Link]();
}
}

Output:

A
B

Extending Interfaces

Interfaces can extend other interfaces.


interface A {
void showA();
}

interface B extends A {
void showB();
}

A class implementing B must implement both methods.

Default and Static Methods (Java 8+)

13
interface Demo {
default void show() {
[Link]("Default method");
}

static void display() {


[Link]("Static method");
}
}

class Test implements Demo {


public static void main(String[] args) {
Test obj = new Test();
[Link]();
[Link]();
}
}

Output:

Default method
Static method

Abstract Class vs Interface

Feature Abstract Class Interface


Methods Abstract + Concrete Mostly abstract
Variables Can have instance variables Only constants
Constructors Present Not present
Inheritance Single Multiple

Important Points

ˆ Interface provides full abstraction


ˆ Supports multiple inheritance
ˆ Methods must be implemented
ˆ Cannot create interface objects
2.7 Inner (Nested) Classes

Introduction to Inner Classes

An inner (nested) class is a class dened inside another class.


ˆ Helps in logical grouping
ˆ Improves encapsulation
ˆ Can access outer class data (including private)
Types of nested classes:
ˆ Static Nested Class
14
ˆ Member Inner Class
ˆ Local Inner Class
ˆ Anonymous Inner Class
1. Static Nested Class
Static Nested Class

Declared using static keyword.


ˆ Does not need outer class object
ˆ Cannot access non-static members directly
class Outer {
static class Inner {
void show() {
[Link]("Static Nested Class");
}
}
}

class Test {
public static void main(String[] args) {
[Link] obj = new [Link]();
[Link]();
}
}

Output:

Static Nested Class

2. Member Inner Class


Member Inner Class

Non-static inner class.


ˆ Requires outer class object
ˆ Can access all members of outer class
class Outer {
int x = 10;

class Inner {
void display() {
[Link](x);
}
}
}

class Test {
public static void main(String[] args) {
Outer o = new Outer();
[Link] i = [Link] Inner();
[Link]();
}
}

15
Output:

10

3. Local Inner Class


Local Inner Class

Declared inside a method.


ˆ Scope limited to method
ˆ Can access nal or eectively nal variables
class Outer {
void show() {
int num = 5;

class Inner {
void display() {
[Link](num);
}
}

Inner obj = new Inner();


[Link]();
}
}

class Test {
public static void main(String[] args) {
new Outer().show();
}
}

Output:

4. Anonymous Inner Class


Anonymous Inner Class

A class without a name, used for one-time use.


abstract class A {
abstract void show();
}

class Test {
public static void main(String[] args) {
A obj = new A() {
void show() {
[Link]("Anonymous Class");
}
};

[Link]();
}
}

16
Output:

Anonymous Class

Important Points

ˆ Inner classes improve encapsulation


ˆ Can access outer class private members
ˆ Anonymous classes used for quick implementations
ˆ Lambda expressions replace many anonymous classes (Java 8+)

17

You might also like