[Go to site: main page, start]

0% found this document useful (0 votes)
17 views18 pages

Java Classes Inheritance Notes

This document provides an overview of Java programming concepts, focusing on classes, inheritance, and object-oriented principles. It covers class fundamentals, object declaration, methods, constructors, recursion, nested classes, multilevel inheritance, method overriding, and abstract classes, along with code examples for each topic. The document serves as a comprehensive guide for B.Tech, BCA, and MCA students learning Java.
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)
17 views18 pages

Java Classes Inheritance Notes

This document provides an overview of Java programming concepts, focusing on classes, inheritance, and object-oriented principles. It covers class fundamentals, object declaration, methods, constructors, recursion, nested classes, multilevel inheritance, method overriding, and abstract classes, along with code examples for each topic. The document serves as a comprehensive guide for B.Tech, BCA, and MCA students learning Java.
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

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.

Common questions

Powered by AI

A class using both default and parameterized constructors demonstrates object initialization by allowing different configurations of initial field settings. The default constructor initializes fields to default values, while the parameterized constructor allows specific values to be set during object creation. For example, in the Person class, the default constructor initializes name to "Unknown" and age to 0, while the parameterized constructor initializes them to specific values provided at instantiation .

Method recursion in Java is applied by defining a method that calls itself with modified parameters. In the factorial example, factorial calls itself by reducing n and multiplying the result by n, while in the Fibonacci series, fib calls itself with n-1 and n-2, summing the results. The base case is critical as it stops the recursive calls, preventing infinite recursion and possible stack overflow. The factorial's base case is when n is 0 or 1, returning 1; for Fibonacci, the base case is when n is less than or equal to 1, returning n .

Multilevel inheritance in Java is implemented by creating a hierarchy where a class inherits from another derived class, forming a lineage (A → B → C). This is accomplished using the extends keyword. For example, in a class hierarchy where Dog extends Mammal, and Mammal extends Animal, each subclass inherits the methods and fields of the classes above it, enabling code reuse across the hierarchy. This inheritance chain allows a Dog object to possess behaviors defined in both Mammal and Animal classes, demonstrating structured code expansion .

Java distinguishes overloaded constructors and methods by differences in their parameter lists, such as the number of parameters, parameter types, or their order. This is a feature of compile-time polymorphism, also known as static binding, as the method or constructor to be invoked is determined during compilation and not at runtime. Unlike method overriding, which supports runtime polymorphism, overloading involves different signatures within the same class context, allowing for multiple forms of method execution based on input .

The 'this' keyword enhances object-oriented programming by resolving naming conflicts between class fields and parameters, facilitating method calling within the same class, enabling constructor chaining, and returning the current object instance. It should be utilized effectively to improve code readability and maintainability by ensuring clarity and avoiding ambiguity, especially when a class method or constructor needs to clearly refer to instance variables .

Inner classes in Java can implement encapsulated helper classes by tightly coupling them within an outer class, allowing direct access to outer class members without external exposure. This encapsulation offers benefits such as improved namespace management, reduced scope of the helper class to the outer class, and enhanced encapsulation by keeping the helper functionality within its related class context. Unlike separate top-level classes, inner classes keep related logic together, promoting code organization and maintainability .

Abstract classes are preferred over interfaces when partial implementation is desired, as an abstract class can include both abstract and concrete methods, allowing shared code. This is beneficial when multiple related classes need consistent functionality with some default behaviors. Conversely, interfaces are ideal for specifying a contract with full abstraction, offering a set of methods that multiple unrelated classes can implement without carrying any implementation details. Using abstract classes is advantageous for shared state or common methods that apply across a hierarchy .

Method overriding provides benefits such as polymorphic behavior, allowing a subclass to provide a specific implementation of a method that is already defined in its parent class, thus enabling runtime polymorphism and promoting code reusability. However, it can introduce complexity and potential performance issues if not used properly, for example, by increasing the level of indirection. Additionally, the overriding method must adhere to strict rules: it cannot be more restrictive than the parent's access modifier, nor can it override static or final methods .

Java's approach to nested classes enhances object-oriented design by encapsulating class definitions within an outer class, promoting a clear and organized code structure. For example, a static nested class allows grouping reusable helper functionality independent of instance-specific context, accessible without an outer class instance. Meanwhile, non-static inner classes can access outer class variables directly, ideal for encapsulating delegated tasks or small components closely tied to the outer class behavior, enabling modular design and reducing namespace clutter .

Java ensures that method overriding is understood at runtime by utilizing dynamic binding, where the method to be invoked is determined by the actual object's type, not the reference type. This contrasts with method overloading, which is resolved at compile-time based on the method signature and argument types through static binding. The runtime system, therefore, identifies the correct overridden method to execute depending on the object class instance rather than the variable type, which is essential for enabling polymorphism .

You might also like