Home Blog Page 95

Inheritance and the super Keyword in Java

0
java spring boot course
java spring boot course

Table of Contents

  1. Introduction to Inheritance
  2. Types of Inheritance in Java
  3. The extends Keyword
  4. Why Use Inheritance?
  5. The super Keyword
    • Accessing Parent Class Members
    • Invoking Parent Class Constructor
  6. Method Overriding in Inheritance
  7. Inheritance with Constructors
  8. Hierarchical vs Multilevel Inheritance
  9. Composition vs Inheritance
  10. Common Pitfalls and Best Practices
  11. Summary

1. Introduction to Inheritance

Inheritance is one of the four fundamental principles of Object-Oriented Programming (OOP), alongside encapsulation, abstraction, and polymorphism. It allows a class (child or subclass) to inherit fields and methods from another class (parent or superclass), promoting code reuse and establishing a logical hierarchy between classes.

For example, if we have a class Vehicle, we can create child classes like Car, Bike, and Truck that inherit the general behavior of Vehicle.


2. Types of Inheritance in Java

Java supports the following types of inheritance:

  • Single Inheritance: One class inherits from another.
  • Multilevel Inheritance: A class inherits from a derived class.
  • Hierarchical Inheritance: Multiple classes inherit from a single parent class.
Java does not support multiple inheritance with classes to avoid ambiguity, but this can be achieved using interfaces.

3. The extends Keyword

To inherit from a class in Java, the extends keyword is used.

class Animal {
void eat() {
System.out.println("This animal eats food");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}

Here, Dog inherits the method eat() from Animal.


4. Why Use Inheritance?

  • Code Reusability: Write common logic once and reuse it across subclasses.
  • Logical Hierarchy: Reflect real-world relationships (e.g., Dog is-an Animal).
  • Method Overriding: Customize behavior in child classes.
  • Maintenance: Easier to manage code in one place.

5. The super Keyword

The super keyword refers to the immediate parent class and is used to:

  • Access parent class methods and variables
  • Call parent class constructor

a. Accessing Parent Class Members

class Animal {
String sound = "Generic Sound";

void displaySound() {
System.out.println("Animal Sound: " + sound);
}
}

class Cat extends Animal {
String sound = "Meow";

void displaySound() {
System.out.println("Cat Sound: " + sound);
System.out.println("Animal Sound: " + super.sound); // Accessing parent member
}
}

b. Invoking Parent Class Constructor

super() is used to call the constructor of the parent class and must be the first statement in the subclass constructor.

class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}

class Dog extends Animal {
Dog() {
super(); // Calls Animal constructor
System.out.println("Dog constructor called");
}
}

This is especially useful when the parent class has a parameterized constructor.


6. Method Overriding in Inheritance

When a child class defines a method with the same signature as one in its parent class, it overrides the parent method.

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Lion extends Animal {
@Override
void sound() {
System.out.println("Lion roars");
}
}

Using super to Access Overridden Method

class Lion extends Animal {
@Override
void sound() {
super.sound(); // Calls parent class method
System.out.println("Lion roars");
}
}

7. Inheritance with Constructors

Constructors are not inherited, but they can be called using super().

class Animal {
Animal(String name) {
System.out.println("Animal name: " + name);
}
}

class Elephant extends Animal {
Elephant() {
super("Elephant"); // Calls parent constructor
System.out.println("Elephant constructor done");
}
}

If the parent class does not have a default (no-argument) constructor, the child class must explicitly call a parameterized one using super.


8. Hierarchical vs Multilevel Inheritance

Hierarchical Inheritance

class Animal { }

class Cat extends Animal { }

class Dog extends Animal { }

class Cow extends Animal { }

Multiple classes share a single base class.

Multilevel Inheritance

class Animal { }

class Mammal extends Animal { }

class Human extends Mammal { }

Inheritance in a chain format—each level builds on the previous one.


9. Composition vs Inheritance

Sometimes, composition is preferred over inheritance, especially when the relationship is has-a rather than is-a.

  • Inheritance: Car is-a Vehicle
  • Composition: Car has-an Engine

Composition increases flexibility, avoids tight coupling, and enhances code maintainability.


10. Common Pitfalls and Best Practices

Pitfalls

  • Overusing inheritance can make the code rigid and hard to refactor.
  • Failing to use super() when necessary in constructors.
  • Forgetting that private members are not accessible in subclasses.
  • Confusing method overriding with method overloading.

Best Practices

  • Prefer composition over inheritance unless is-a clearly applies.
  • Always mark overridden methods with @Override for clarity and compile-time checks.
  • Avoid deep inheritance hierarchies; use interfaces where applicable.
  • Ensure constructors properly invoke parent constructors for initialization.

11. Summary

Inheritance in Java is a cornerstone of OOP that enables efficient code reuse and logical relationships between classes. The super keyword enhances control over parent-child interactions, whether it’s accessing variables, methods, or constructors. When used wisely, inheritance can lead to elegant and maintainable designs, but it must be applied with clear intent and good understanding of when alternatives like composition are better suited.

Today in History – 24 April

0
today in history 24 april

today in history 24 april

1311

General Malik Kafur returns to Delhi after campaign in South India.

1800

President John Adams approves legislation to appropriate $5,000 to purchase “such books as may be necessary for the use of Congress,” thus establishing the Library of Congress. The first books, ordered from London, arrived in 1801 and were stored in the U.S. Capitol, the library’s first home.

1858

Kunwar Singh, revolutionary of Indian mutiny and freedom fighter, passed away. He fought his last battle near Jagdishpur, Bihar on April 23, 1858 and defeated the Britishers but was deeply wounded. He also organised the national rebels.

1916

On Easter Monday in Dublin, the Irish Republican Brotherhood, a secret organization of Irish nationalists led by Patrick Pearse, launches the so-called Easter Rebellion, an armed uprising against British rule.

1922

Colin Ross is hanged to death in Australia for the rape and murder of 13-year-old Alma Tirtschke. Ross was one of the first criminals in Australia to be convicted based on forensic evidence.

1929

First non-stop flight from England to India takes-off.

1932

450 people seized by British for defying ban on Indian National Congress.

1959

Nehru meets the exiled Dalai Lama in Mussoorie.

1965

Kosi Barrage inaugurated by King Mahendra of Nepal.

1973

Sachin Ramesh Tendulkar, cricketer (prodigy at 16, Indian capt at 23), was born in Bombay.

1996

SC holds that bank managers acting beyond their authority in allowing overdrafts and passing cheques would be amounted to committing misconduct.

Related Articles: 

Today in History – 23 April

Today in History – 22 April

Today in History – 21 April

Today in History – 20 April

Constructors and the this Keyword in Java

0
java spring boot course
java spring boot course

Table of Contents

  1. Introduction
  2. What is a Constructor?
  3. Types of Constructors
    • Default Constructor
    • Parameterized Constructor
    • Constructor Overloading
  4. Purpose of Constructors
  5. The this Keyword
    • Referring to Instance Variables
    • Calling Constructors
    • Passing Current Object
    • Returning Current Object
  6. Constructor vs Method
  7. Common Pitfalls and Best Practices
  8. Summary

1. Introduction

Constructors are special methods in Java used to initialize objects. When you create a new object using the new keyword, the constructor of the class is automatically invoked. This module will explore how constructors work, how to overload them, and how the this keyword enhances clarity and functionality in object-oriented design.


2. What is a Constructor?

A constructor is a block of code that is called when an instance (object) of a class is created. It has the same name as the class and no return type—not even void.

Basic Syntax:

class MyClass {
MyClass() {
// Constructor code
}
}

Constructors can be used to assign default or user-defined values to instance variables when an object is instantiated.


3. Types of Constructors

a. Default Constructor

If you don’t define any constructor in your class, Java provides a default constructor automatically. This constructor does nothing and is used to create an object without any initial values.

class Book {
String title;
int pages;
}

public class Main {
public static void main(String[] args) {
Book b1 = new Book(); // Implicit default constructor is used
System.out.println(b1.title); // null
System.out.println(b1.pages); // 0
}
}

If you define any constructor yourself, Java no longer provides the default one automatically.


b. Parameterized Constructor

You can define constructors that accept parameters to initialize your object with specific values.

class Book {
String title;
int pages;

Book(String t, int p) {
title = t;
pages = p;
}
}

Now you can create objects with custom values:

Book b = new Book("Effective Java", 416);

c. Constructor Overloading

Constructor overloading allows you to define multiple constructors with different parameter lists within the same class.

class Book {
String title;
int pages;

Book() {
this("Unknown", 0); // Calls another constructor
}

Book(String t) {
this(t, 100); // Default pages if only title is given
}

Book(String t, int p) {
title = t;
pages = p;
}
}

This provides flexibility in object creation and is a powerful example of compile-time polymorphism.


4. Purpose of Constructors

Constructors serve the following main purposes:

  • Initialize instance variables
  • Allocate system resources, if needed
  • Enforce mandatory fields at object creation
  • Enhance readability and maintainability by controlling initialization logic

You should use constructors instead of setters if some values are mandatory to create a valid object.


5. The this Keyword

The this keyword is a reference to the current object. It’s particularly useful in constructors to distinguish between instance variables and parameters or to invoke another constructor.

a. Referring to Instance Variables

When parameter names shadow instance variables, use this to resolve ambiguity:

class Book {
String title;

Book(String title) {
this.title = title; // Refers to instance variable
}
}

Without this, the assignment would be ambiguous and ineffective.


b. Calling Constructors

You can call another constructor from within a constructor using this():

class Book {
String title;
int pages;

Book() {
this("Default Title", 100); // Calls another constructor
}

Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
}

this() must be the first statement in the constructor.


c. Passing Current Object

The current object can be passed as an argument using this. This is useful in chaining or callback patterns.

class Book {
void print(Book b) {
System.out.println("Title: " + b.title);
}

void display() {
print(this); // Passing current object
}
}

d. Returning Current Object

Methods can also return the current object using this. This enables method chaining.

class Book {
String title;

Book setTitle(String title) {
this.title = title;
return this;
}

Book print() {
System.out.println(title);
return this;
}
}
new Book().setTitle("Clean Code").print();

6. Constructor vs Method

FeatureConstructorMethod
NameSame as classAny valid identifier
Return TypeNone (not even void)Must have a return type
InvocationAutomatically during object creationExplicitly using object reference
PurposeInitialize objectPerform operations
Overloading AllowedYesYes
InheritanceNot inheritedInherited

7. Common Pitfalls and Best Practices

Pitfalls

  • Not using this when instance variables are shadowed
  • Attempting to return a value from a constructor
  • Calling this() after a statement in a constructor (must be the first line)

Best Practices

  • Use this only when necessary to reduce verbosity.
  • Always initialize required fields using constructors.
  • Prefer constructor chaining to reduce duplicate code.
  • Avoid performing heavy operations in constructors; keep them lightweight.
  • Use parameterized constructors for better flexibility and clarity.

8. Summary

In this module, you’ve learned:

  • What constructors are and why they are used
  • Differences between default, parameterized, and overloaded constructors
  • The use of the this keyword in accessing variables, calling constructors, and enabling method chaining
  • How constructors differ from methods
  • Best practices for writing clean and efficient constructors

Understanding constructors and the this keyword lays the foundation for advanced object creation strategies, such as factory methods, builder patterns, and dependency injection.

Classes and Objects in Java

0
java spring boot course
java spring boot course

Table of Contents

  1. Introduction to Classes and Objects
  2. Defining a Class
  3. Fields (Instance Variables)
  4. Methods in a Class
  5. Creating Objects
  6. Memory Allocation for Objects
  7. Accessing Members using Objects
  8. Multiple Objects of the Same Class
  9. Anonymous Objects
  10. Summary and Best Practices

1. Introduction to Classes and Objects

Classes and objects are the foundation of object-oriented programming in Java. A class serves as a blueprint for creating objects, while an object is an instance of a class. Classes define properties and behaviors, and objects represent real-world entities with those properties and behaviors.

Understanding how classes and objects work is essential for building modular, maintainable, and scalable Java applications.


2. Defining a Class

In Java, a class is defined using the class keyword. It may contain fields (variables), methods, constructors, blocks, and nested classes or interfaces.

Syntax:

class ClassName {
// Fields
// Methods
}

Example:

class Car {
String color;
int speed;

void drive() {
System.out.println("Driving at " + speed + " km/h");
}
}

In the example above, Car is a class with two fields (color and speed) and one method drive().


3. Fields (Instance Variables)

Fields, also called instance variables, are variables declared inside a class but outside any method. Each object of the class gets its own copy of the instance variables.

class Student {
String name;
int age;
}

Each Student object will have its own name and age.


4. Methods in a Class

Methods define the behavior of the class. They are blocks of code that perform specific actions and can access the class’s fields.

class Student {
String name;
int age;

void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

Methods can be parameterized, return values, or be void (return nothing). They help encapsulate the logic that operates on the class’s data.


5. Creating Objects

An object is created using the new keyword followed by the class constructor.

Student s1 = new Student();

This statement creates a new Student object and assigns it to reference variable s1.

Each time you use new, a new object is created in memory with its own copy of instance variables.


6. Memory Allocation for Objects

When a Java object is created:

  • Memory is allocated for instance variables in the heap memory.
  • Local variables and references (like s1 in the above example) are stored in stack memory.
  • The object’s methods are stored in method area.

Each object has its own copy of non-static fields, ensuring isolation and independence between instances.


7. Accessing Members using Objects

Object members (fields and methods) are accessed using the dot operator (.).

Student s1 = new Student();
s1.name = "Alice";
s1.age = 22;
s1.displayInfo(); // Output: Name: Alice, Age: 22

You can modify field values or call methods through object references.


8. Multiple Objects of the Same Class

You can create multiple objects from the same class, each with their own field values.

Student s1 = new Student();
s1.name = "Alice";
s1.age = 22;

Student s2 = new Student();
s2.name = "Bob";
s2.age = 25;

Each object maintains its own state. Changing one object’s data does not affect another.


9. Anonymous Objects

An anonymous object is created without a reference variable. These are typically used for a single-use purpose, such as method invocation.

new Student().displayInfo(); // Creates a Student object and calls displayInfo()

Although convenient, anonymous objects cannot be reused since there’s no reference to access them again.

Use anonymous objects when object reuse is unnecessary, such as in testing or method chaining.


10. Summary and Best Practices

Summary

  • A class defines the structure (fields) and behavior (methods) for its objects.
  • An object is an instance of a class created using the new keyword.
  • Objects are stored in heap memory, while their references are on the stack.
  • Each object maintains its own state through its fields.
  • Methods define what an object can do and can be invoked through object references.

Best Practices

  • Use meaningful class and object names (e.g., Student, Employee, BankAccount).
  • Keep fields private and use getters/setters to enforce encapsulation.
  • Avoid using unnecessary public fields as it breaks encapsulation.
  • Prefer creating named objects unless there’s a strong reason for anonymity.
  • Structure classes logically, keeping related data and behavior together.

Object-Oriented Programming – Basics and Concepts

0
java spring boot course
java spring boot course

Table of Contents

  1. Introduction to Object-Oriented Programming (OOP)
  2. Core Principles of OOP
  3. Classes and Objects
  4. Constructors
  5. The this Keyword
  6. Encapsulation
  7. Inheritance
  8. Polymorphism
  9. Abstraction
  10. Summary and Best Practices

1. Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. Java is a fully object-oriented language (with minor exceptions like primitive types) and leverages OOP principles to create reusable, scalable, and maintainable applications.

OOP enables you to model real-world systems more naturally, where everything is treated as an object with properties (fields) and behaviors (methods).


2. Core Principles of OOP

There are four fundamental principles of OOP:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

These principles work together to provide a flexible and powerful design structure.


3. Classes and Objects

Class

A class is a blueprint for creating objects. It defines the properties and behaviors of the objects.

class Car {
String brand;
int speed;

void drive() {
System.out.println("Driving at " + speed + " km/h");
}
}

Object

An object is an instance of a class.

public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.speed = 120;
myCar.drive(); // Outputs: Driving at 120 km/h
}
}

Each object created from the same class has its own set of variables and can perform methods defined in the class.


4. Constructors

A constructor is a special method that is called when an object is instantiated. Its name is the same as the class name and it has no return type.

Example:

class Car {
String brand;

Car(String brandName) {
brand = brandName;
}
}

You can also have default constructors (no parameters) or parameterized constructors.

Java supports constructor overloading, where multiple constructors with different parameter lists are defined in the same class.


5. The this Keyword

The this keyword is a reference to the current object. It is used to distinguish class fields from parameters with the same name.

class Car {
String brand;

Car(String brand) {
this.brand = brand; // Refers to class field, not constructor parameter
}
}

It can also be used to call other constructors within the same class using this() and to pass the current object as an argument.


6. Encapsulation

Encapsulation is the process of bundling data (fields) and methods that operate on that data into a single unit, i.e., a class. It also involves restricting direct access to some of an object’s components, which is usually done using access modifiers like private, public, and protected.

Example:

class Account {
private double balance;

public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

public double getBalance() {
return balance;
}
}

Here, the balance field is private and only accessible through public methods, enforcing controlled access.


7. Inheritance

Inheritance allows a class to inherit fields and methods from another class. The class that inherits is called the subclass, and the class being inherited from is the superclass.

Example:

class Vehicle {
void start() {
System.out.println("Vehicle starting...");
}
}

class Car extends Vehicle {
void honk() {
System.out.println("Car honking...");
}
}

Now Car has both start() and honk() methods.

Java supports single inheritance but not multiple inheritance through classes (it supports it via interfaces).


8. Polymorphism

Polymorphism allows objects to be treated as instances of their parent class rather than their actual class.

Compile-Time Polymorphism (Method Overloading)

We already saw this in the Methods module—same method name, different parameters.

Run-Time Polymorphism (Method Overriding)

Occurs when a subclass provides a specific implementation of a method already defined in its superclass.

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
Animal obj = new Dog();
obj.sound(); // Outputs: Dog barks

The method that gets called is determined at runtime, not compile time.


9. Abstraction

Abstraction is the process of hiding the internal details and showing only the essential features.

Java supports abstraction through:

  • Abstract classes – cannot be instantiated and can contain abstract methods
  • Interfaces – fully abstract types in earlier versions of Java, but since Java 8, interfaces can have default and static methods too

Abstract class example:

abstract class Shape {
abstract void draw();
}

class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}

You cannot create an object of Shape, but you can of Circle, which implements the abstract method.


10. Summary and Best Practices

In this module, we explored:

  • The foundation of Object-Oriented Programming in Java
  • How classes and objects model real-world entities
  • The use of constructors and this keyword
  • Encapsulation for data hiding
  • Inheritance for code reusability
  • Polymorphism for flexible method behavior
  • Abstraction for hiding implementation complexity

Best Practices:

  • Favor encapsulation to protect internal state.
  • Use inheritance judiciously; prefer composition when inheritance isn’t appropriate.
  • Override methods responsibly and always use @Override.
  • Make classes and methods only as accessible as necessary (private by default).
  • Use interfaces to define contracts for unrelated classes.