Java Programming
d Notes with Code Examples
Classes & Inheritance
Unit II | [Link] / BCA / MCA | Java
1. Class Fundamentals
A class is a blueprint or template that defines the properties (fields) and behaviors (methods) of objects. It
is the fundamental building block of object-oriented programming in Java.
Syntax of a Class
class ClassName {
// Fields (attributes/variables)
dataType fieldName;
// Methods (behaviors)
returnType methodName(parameters) {
// method body
}
}
Example: Basic Class
class Student {
// Fields
String name;
int age;
double marks;
// Method
void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Marks: " + marks);
}
}
// Main class
class Main {
public static void main(String[] args) {
Student s = new Student(); // Creating object
[Link] = "Rahul";
[Link] = 20;
[Link] = 85.5;
[Link]();
}
}
■ Output: Name: Rahul | Age: 20 | Marks: 85.5
Key Terminology
• Class — Blueprint/template for creating objects.
• Object — Instance of a class. Each object has its own copy of instance variables.
• Field / Instance Variable — Variable declared inside a class but outside any method.
• Method — Function defined inside a class to describe behavior.
• new keyword — Allocates memory and creates an object at runtime.
2. Declaring Objects
Creating an object involves two steps: Declaration (creating a reference variable) and Instantiation
(allocating memory using new).
// Step 1: Declaration
ClassName objectName;
// Step 2: Instantiation
objectName = new ClassName();
// Both steps combined
ClassName objectName = new ClassName();
Example: Declaring and Using Objects
class Box {
double width, height, depth;
double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String[] args) {
Box b1 = new Box(); // Object 1
Box b2 = new Box(); // Object 2
[Link] = 10;
[Link] = 5;
[Link] = 3;
[Link] = 7;
[Link] = 4;
[Link] = 2;
[Link]("Volume of b1: " + [Link]()); // 150.0
[Link]("Volume of b2: " + [Link]()); // 56.0
}
}
■ Each object (b1, b2) has its own independent copies of width, height, depth.
3. Introducing Methods
A method is a block of code that performs a specific task. Methods define the behavior of objects and
promote code reusability.
Method Syntax
returnType methodName(parameterList) {
// method body
return value; // only if returnType is not void
}
Types of Methods
class Calculator {
// Method with no parameters, no return value
void greet() {
[Link]("Welcome to Calculator!");
}
// Method with parameters, no return value
void add(int a, int b) {
[Link]("Sum = " + (a + b));
}
// Method with parameters and return value
int multiply(int a, int b) {
return a * b;
}
// Method returning boolean
boolean isEven(int n) {
return n % 2 == 0;
}
}
class Test {
public static void main(String[] args) {
Calculator c = new Calculator();
[Link](); // Welcome to Calculator!
[Link](5, 3); // Sum = 8
[Link]([Link](4, 6)); // 24
[Link]([Link](10)); // true
}
}
■ void means the method does not return any value. The return statement exits the method.
4. Constructors
A constructor is a special method that is automatically called when an object is created. It is used to
initialize the object's fields.
Rules for Constructors
• Constructor name must be the same as the class name.
• Constructor has no return type (not even void).
• Called automatically when object is created using new.
• If no constructor is defined, Java provides a default constructor.
Default vs Parameterized Constructor
class Person {
String name;
int age;
// Default Constructor
Person() {
name = "Unknown";
age = 0;
[Link]("Default constructor called");
}
// Parameterized Constructor
Person(String n, int a) {
name = n;
age = a;
[Link]("Parameterized constructor called");
}
void display() {
[Link](name + " | Age: " + age);
}
}
class Main {
public static void main(String[] args) {
Person p1 = new Person(); // Default constructor
Person p2 = new Person("Ananya", 21); // Parameterized constructor
[Link](); // Unknown | Age: 0
[Link](); // Ananya | Age: 21
}
}
5. The 'this' Keyword
The this keyword refers to the current object inside a method or constructor. It is used to resolve naming
conflicts between instance variables and parameters.
Uses of 'this'
class Employee {
String name;
int salary;
// Use 1: Resolve ambiguity between field and parameter
Employee(String name, int salary) {
[Link] = name; // '[Link]' = instance variable
[Link] = salary; // 'name' alone = parameter
}
// Use 2: Call another method of the same class
void show() {
[Link]([Link] + " earns " + [Link]);
}
// Use 3: Call another constructor (constructor chaining)
Employee() {
this("Unknown", 0); // calls Employee(String, int)
[Link]("Default Employee created");
}
// Use 4: Return current object
Employee getEmployee() {
return this;
}
}
class Main {
public static void main(String[] args) {
Employee e1 = new Employee("Raj", 50000);
[Link](); // Raj earns 50000
Employee e2 = new Employee();
[Link](); // Unknown earns 0
}
}
■ 'this()' call must be the first statement inside a constructor when used for chaining.
6. Overloading Constructors
Constructor overloading means defining multiple constructors in the same class with different parameter
lists. Java differentiates them by number, type, or order of parameters.
class Rectangle {
double length, width;
// Constructor 1: No parameters (square with side 1)
Rectangle() {
length = 1;
width = 1;
}
// Constructor 2: One parameter (square)
Rectangle(double side) {
length = side;
width = side;
}
// Constructor 3: Two parameters
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}
void display() {
[Link]("Length=" + length + " Width=" + width
+ " Area=" + area());
}
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(); // 1x1
Rectangle r2 = new Rectangle(5); // 5x5
Rectangle r3 = new Rectangle(4, 6); // 4x6
[Link](); // Length=1.0 Width=1.0 Area=1.0
[Link](); // Length=5.0 Width=5.0 Area=25.0
[Link](); // Length=4.0 Width=6.0 Area=24.0
}
}
■ This is also called compile-time polymorphism or static binding.
7. Recursion
A method that calls itself is called a recursive method. Recursion breaks a problem into smaller
subproblems of the same type. Every recursive method must have a base case to stop infinite recursion.
Example 1: Factorial
class Recursion {
// Factorial using recursion
int factorial(int n) {
if (n == 0 || n == 1) // Base case
return 1;
return n * factorial(n - 1); // Recursive call
}
public static void main(String[] args) {
Recursion r = new Recursion();
[Link]("5! = " + [Link](5)); // 120
[Link]("6! = " + [Link](6)); // 720
}
}
// How it works:
// factorial(5) = 5 * factorial(4)
// = 5 * 4 * factorial(3)
// = 5 * 4 * 3 * factorial(2)
// = 5 * 4 * 3 * 2 * factorial(1)
// = 5 * 4 * 3 * 2 * 1 = 120
Example 2: Fibonacci Series
class Fibonacci {
int fib(int n) {
if (n <= 1) return n; // Base case: fib(0)=0, fib(1)=1
return fib(n-1) + fib(n-2); // Recursive case
}
public static void main(String[] args) {
Fibonacci f = new Fibonacci();
[Link]("Fibonacci: ");
for (int i = 0; i < 8; i++) {
[Link]([Link](i) + " "); // 0 1 1 2 3 5 8 13
}
}
}
■ Always define a base case to prevent StackOverflowError in recursive methods.
8. Nested and Inner Classes
A class defined inside another class is called a nested class. Java supports four types of nested classes.
• Static Nested Class — Declared with static keyword. Can be accessed without outer class object.
• Non-static Inner Class — Most common. Requires outer class object to instantiate.
• Local Inner Class — Defined inside a method. Scope limited to that method.
• Anonymous Inner Class — A class without a name, used for one-time use.
Non-static Inner Class Example
class Outer {
int x = 100;
class Inner {
int y = 200;
void display() {
// Inner class can access outer class members directly
[Link]("Outer x = " + x);
[Link]("Inner y = " + y);
}
}
}
class Main {
public static void main(String[] args) {
Outer outer = new Outer();
[Link] inner = [Link] Inner(); // Create inner object
[Link]();
// Output:
// Outer x = 100
// Inner y = 200
}
}
Static Nested Class Example
class Outer {
static int staticVar = 50;
static class StaticNested {
void show() {
[Link]("Static var = " + staticVar);
}
}
}
class Main {
public static void main(String[] args) {
// No outer object needed for static nested class
[Link] obj = new [Link]();
[Link](); // Static var = 50
}
}
9. Creating Multilevel Hierarchy
In multilevel inheritance, a class inherits from a derived class, forming a chain. The extends keyword is
used to inherit from a parent class. Java supports single and multilevel inheritance, but NOT multiple
inheritance through classes.
Syntax
class A { ... } // Grandparent
class B extends A { ... } // Parent (inherits A)
class C extends B { ... } // Child (inherits B, and indirectly A)
Example: Animal → Mammal → Dog
class Animal {
String name;
void eat() {
[Link](name + " is eating.");
}
void breathe() {
[Link](name + " breathes oxygen.");
}
}
class Mammal extends Animal {
void feedMilk() {
[Link](name + " feeds milk to young.");
}
}
class Dog extends Mammal {
String breed;
Dog(String name, String breed) {
[Link] = name;
[Link] = breed;
}
void bark() {
[Link](name + " (" + breed + ") says: Woof!");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex", "German Shepherd");
[Link](); // From Animal
[Link](); // From Animal
[Link](); // From Mammal
[Link](); // Own method
}
}
■ Dog inherits all accessible methods from both Mammal and Animal. This is the power of multilevel
inheritance.
'super' Keyword in Multilevel Hierarchy
The super keyword refers to the immediate parent class. It is used to call the parent's constructor or
method.
class Vehicle {
String type;
Vehicle(String type) {
[Link] = type;
[Link]("Vehicle: " + type);
}
void info() {
[Link]("Type: " + type);
}
}
class Car extends Vehicle {
String brand;
Car(String type, String brand) {
super(type); // Call Vehicle constructor
[Link] = brand;
[Link]("Car Brand: " + brand);
}
void info() {
[Link](); // Call parent method
[Link]("Brand: " + brand);
}
}
class ElectricCar extends Car {
int range;
ElectricCar(String brand, int range) {
super("Electric", brand); // Call Car constructor
[Link] = range;
}
void display() {
info();
[Link]("Range: " + range + " km");
}
}
class Main {
public static void main(String[] args) {
ElectricCar ec = new ElectricCar("Tesla", 500);
[Link]();
}
}
10. Method Overriding
When a subclass provides a specific implementation of a method that is already defined in its parent
class, it is called method overriding. The method in the subclass must have the same name, return type,
and parameter list.
Rules for Method Overriding
• Method name, return type, and parameters must be identical.
• Overriding is only possible through inheritance.
• The access modifier cannot be more restrictive than the parent's.
• static and final methods cannot be overridden.
• Use @Override annotation for clarity and compile-time checks.
Example
class Shape {
void draw() {
[Link]("Drawing a generic shape");
}
double area() {
return 0;
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
[Link] = radius;
}
@Override
void draw() {
[Link]("Drawing a Circle");
}
@Override
double area() {
return [Link] * radius * radius;
}
}
class Triangle extends Shape {
double base, height;
Triangle(double base, double height) {
[Link] = base;
[Link] = height;
}
@Override
void draw() {
[Link]("Drawing a Triangle");
}
@Override
double area() {
return 0.5 * base * height;
}
}
class Main {
public static void main(String[] args) {
Shape s = new Shape();
Shape c = new Circle(7);
Shape t = new Triangle(5, 10);
[Link](); // Drawing a generic shape
[Link](); // Drawing a Circle <- Overridden
[Link](); // Drawing a Triangle <- Overridden
[Link]("Circle area: %.2f%n", [Link]()); // 153.94
[Link]("Triangle area: %.2f%n", [Link]()); // 25.00
}
}
■ This demonstrates Runtime Polymorphism — the method called depends on the actual object type, not the
reference type.
Overriding vs Overloading
Feature Method Overriding Method Overloading
Location Different classes (parent-child) Same class
Parameters Must be identical Must be different
Return Type Must be same Can be different
Binding Runtime (dynamic) Compile time (static)
Keyword @Override annotation No special keyword
11. Abstract Classes
An abstract class is a class that cannot be instantiated (you cannot create its object directly). It is
declared using the abstract keyword and can contain both abstract methods (no body) and concrete
methods (with body).
Key Points
• Declared with the abstract keyword.
• Can have abstract methods (without body) and non-abstract methods (with body).
• Cannot create an object of an abstract class.
• A subclass must override all abstract methods, otherwise it too must be abstract.
• Can have constructors, fields, and static methods.
• Used to provide a common base with partial implementation.
Syntax
abstract class ClassName {
// Abstract method (no body, must be overridden)
abstract returnType methodName();
// Concrete method (has body, can be used directly)
void concreteMethod() {
[Link]("Concrete method in abstract class");
}
}
Example: Abstract Class in Action
abstract class Animal {
String name;
Animal(String name) {
[Link] = name;
}
// Abstract methods - must be overridden
abstract void makeSound();
abstract String getType();
// Concrete method - shared by all animals
void sleep() {
[Link](name + " is sleeping.");
}
void introduce() {
[Link]("I am " + name + ", a " + getType());
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
void makeSound() {
[Link](name + " says: Woof! Woof!");
}
@Override
String getType() {
return "Dog";
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
@Override
void makeSound() {
[Link](name + " says: Meow!");
}
@Override
String getType() {
return "Cat";
}
}
class Cow extends Animal {
Cow(String name) {
super(name);
}
@Override
void makeSound() {
[Link](name + " says: Moo!");
}
@Override
String getType() {
return "Cow";
}
}
class Main {
public static void main(String[] args) {
// Animal a = new Animal("X"); // ERROR! Cannot instantiate
Animal[] animals = {
new Dog("Rex"),
new Cat("Whiskers"),
new Cow("Bessie")
};
for (Animal a : animals) {
[Link](); // Concrete method
[Link](); // Polymorphic call
[Link](); // Concrete method
[Link]();
}
}
}
■ Abstract classes are ideal when you want to provide common code to subclasses while forcing them to
implement certain behaviors.
Abstract Class vs Interface
Feature Abstract Class Interface
Keyword abstract class interface
Methods Abstract + Concrete Abstract (default: all)
Variables Any type public static final only
Constructor Yes No
Multiple Inherit No (single only) Yes (multiple)
Access Modifiers Any public by default
When to Use Partial implementation Full abstraction / contract
★. Quick Revision Summary
Class Blueprint for objects. Contains fields and methods.
Object Instance of a class. Created using 'new'.
Constructor Special method to initialize objects. Same name as class, no return type.
this Refers to the current object. Resolves naming conflicts.
Constructor Overloading Multiple constructors with different parameters in same class.
Recursion Method calling itself. Must have a base case.
Inner Class Class defined inside another class. Can access outer class members.
Multilevel Inheritance Chain: A → B → C. Use 'extends' keyword.
super Refers to parent class. Used to call parent constructor/method.
Method Overriding Subclass redefines parent method. Runtime polymorphism.
Abstract Class Cannot be instantiated. Has abstract (no body) and concrete methods.
These notes cover all key concepts of Java Classes & Inheritance as per standard [Link] / BCA / MCA syllabus.