Mostrando postagens com marcador inheritance. Mostrar todas as postagens
Mostrando postagens com marcador inheritance. Mostrar todas as postagens

Inheritance and Polymorphism

Inheritance and polymorphism are two key concepts in object-oriented programming (OOP) that facilitate code reuse, extensibility, and flexibility. Let's explore these concepts in Java:


Inheritance

Inheritance is the mechanism by which one class (subclass or derived class) inherits the properties and behaviors of another class (superclass or base class). It promotes code reuse by allowing subclasses to inherit fields and methods from their superclass.


Syntax

public class Superclass {
    // Fields and methods
}

public class Subclass extends Superclass {
    // Additional fields and methods
}


Example

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

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks.");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat meows.");
    }
}


Polymorphism

Polymorphism is the ability of an object to take on different forms. In Java, polymorphism is achieved through method overriding and method overloading.


Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. It allows objects of different classes to be treated as objects of a common superclass.

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

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks.");
    }
}

public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat meows.");
    }
}


Method Overloading

Method overloading occurs when a class has multiple methods with the same name but different parameter lists. It allows methods to behave differently based on the number or type of parameters passed to them.

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}


Polymorphic Behavior

Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.makeSound(); // Outputs: Dog barks.
animal2.makeSound(); // Outputs: Cat meows.


Conclusion

Inheritance and polymorphism are powerful concepts in Java that enable code reuse, extensibility, and flexibility in object-oriented programming. Inheritance allows subclasses to inherit fields and methods from their superclass, while polymorphism allows objects to take on different forms through method overriding and method overloading. Understanding and applying these concepts effectively can lead to well-designed and maintainable Java applications.

Sealed

Sealed classes and interfaces in Java, introduced in Java 17, provide a way to restrict the inheritance hierarchy of classes and interfaces. When a class or interface is sealed, it specifies which classes or interfaces are allowed to be its direct subclasses or implementers. This enhances the control over the abstraction and encapsulation of types in Java, making the design more robust and secure.

Here's a simple example to illustrate sealed classes and interfaces.

Let's define a sealed interface "Shape" that can be implemented by only specific classes.

public sealed interface Shape permits Circle, Rectangle {
    double area();
}

In this example, the "Shape" interface is sealed, and it specifies that only classes "Circle" and "Rectangle" are permitted to directly implement the "Shape" interface.

Now, let's define the subclasses "Circle" and "Rectangle".

public final class Circle implements Shape {
    private final double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

public final class Rectangle implements Shape {
    private final double width;
    private final double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }
}

In this example, "Circle" and "Rectangle" are permitted to implement the "Shape" interface because they are explicitly listed in the "permits" clause of the "Shape" interface declaration.

Now, let's try to define another class "Triangle" that attempts to implement the "Shape" interface.

// error: triangle is not allowed to extend Shape as it is not listed in the permits clause
public final class Triangle implements Shape {
    // implementation omitted
}

Since "Triangle" is not listed in the "permits" clause of the "Shape" interface, attempting to implement the "Shape" interface with "Triangle" will result in a compilation error.

Sealed classes and interfaces provide better control over class hierarchies, allowing developers to specify and enforce constraints on subclassing and implementation relationships, leading to more maintainable and secure codebases.

What are Interfaces in Java

In Java, an interface is a collection of abstract methods (without implementation) and constants (final variables) that can be implemented by classes. Interfaces allow the definition of a class contract must follow, specifying the methods that must be implemented by any class that implements the interface. Furthermore, a class can implement multiple interfaces, thus providing a form of multiple inheritance in Java.
Here are some key points about interfaces in Java:

Interface Declaration

To declare an interface in Java, the "interface" keyword is used. Methods declared in an interface are implicitly public and abstract.

public interface MyInterface {
     void method1();
     int method2();
}

Interface Implementation

To implement an interface in a class, use the "implements" keyword. The class must provide an implementation for all methods declared in the interface.

public class MyClass implements MyInterface {
     @Override
     public void method1() {
         // Implementation of method1
     }
     @Override
     public int method2() {
         // Implementation of method2
         return 42;
     }
}

Multiple Inheritance with Interfaces

Unlike classes, a class can implement multiple interfaces. This provides a form of multiple inheritance in Java, which is not allowed for classes.

public class MyClass implements Interface1, Interface2 {
     // Implementation of interface methods
}

Constants in Interfaces

Interfaces can contain constants, which are implicitly public, static, and final. Starting from Java 8, interfaces can also have methods with default implementation (default methods) and static methods.

public interface MyInterface {
     int CONSTANT = 42; // Constant
     void method1(); // Abstract method
     default void defaultmethod() {
         // Default implementation for the method (as of Java 8)
     }
}


Polymorphism by Interfaces

Polymorphism in Java is often achieved through the use of interfaces. An interface reference can point to an object of any class that implements that interface, providing flexibility and extensibility in code design.

MyInterface object = new MyClass();


Interfaces play an important role in software development in Java, facilitating the creation of modular code, promoting polymorphism, and allowing the implementation of clear contracts between classes.

How Java supports Inheritance

Inheritance is one of the fundamental principles of object-oriented programming. Inheritance allows a class (subclass) to inherit characteristics and behaviors from another class (superclass). Here are some ways Java supports inheritance:


Keyword "extends"

The "extends" keyword is used to establish an inheritance relationship between two classes. The subclass extends the superclass, thus acquiring the attributes and methods of the superclass.

public class Animal {
     // superclass attributes and methods
}
public class Dog extends Animal {
     // subclass-specific attributes and methods
}


Attributes and Methods Inheritance

The subclass inherits attributes and methods from the superclass, allowing code reuse.

Dog myDog = new Dog();
myDog.setName("Rex"); // Animal superclass method
myDog.bark(); // Dog subclass specific method


Method "super"

The "super" keyword is used to call superclass methods or access attributes from the subclass.

public class Dog extends Animal {
     public void bark() {
         super.makeSound(); // calls method makeSound() of superclass Animal
         System.out.println("Dog Barking");
     }
}


Override

The subclass can provide a specific implementation for a method that is already defined in the superclass. This is known as method overriding.

@Override
public void makeSound() {
     System.out.println("Dog Barking");
}

Polymorphism

Polymorphism is supported in Java, allowing references from a superclass to be used to manipulate objects from subclasses.

Animal myAnimal = new Dog(); // polymorphism 
myAnimal.makeSound(); // invoke the specific Dog subclass method

Constructors in the Inheritance Hierarchy

Constructors in the inheritance hierarchy are called in the correct order, ensuring that necessary initializations are made to all classes.

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

public class Dog extends Animal {
     public Dog() {
         super(); // call the Animal superclass constructor
         System.out.println("Dog subclass constructor");
     }
}

These are some main aspects through which Java supports inheritance. It is a powerful tool for creating class hierarchies, promoting code reuse, flexibility and extensibility in object-oriented software development.

HashMap in Java

Let’s break down how   HashMap   works internally (Java 8+ implementation). What Is a HashMap? HashMap<K, V>  is a  hash table–based  ...