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