Posts

Showing posts with the label Runtime Polymorphism

Polymorphism in Java: Definition, Types, and Examples

Polymorphism in Java Polymorphism is an object-oriented programming concept in which a single reference variable can exhibit different behaviors depending on the object it refers to. Types of Polymorphism Polymorphism in Java is classified into two types: Compile-Time Polymorphism Run-Time Polymorphism 1. Compile-Time Polymorphism In compile-time polymorphism, the method resolution is performed by the compiler. Key Points The compiler resolves the method call based on the parameter list. Once method resolution is done, the compiler performs static binding. In static binding:               ✓ The method declaration is bound to the method definition at compile time. Compile-time polymorphism is achieved using method overloading. Example class Calculator {     int add(int a, int b) {         return a + b;     }     double add(double a, double b) {         return a + b;     } } ...

Up Casting in Java: Definition, Rules, and Examples

Up Casting in Java Up Casting is the process of assigning a subclass object to a superclass reference or a super-interface reference. Key Points Up casting is also known as implicit casting. It is performed automatically by the compiler. In up casting, the compiler treats the subclass object as a superclass object. No explicit cast is required. Parent p = new Child(); // Up casting Accessing Members During Up Casting When up casting occurs, the programmer can access only the members of the superclass using the superclass reference. Subclass-specific members cannot be accessed directly. class Parent {     void show() {         System.out.println("Parent method");     } } class Child extends Parent {     void display() {         System.out.println("Child method");     } } Parent p = new Child(); p.show(); // Allowed // p.display(); // Not allowed Up Casting with Method Overriding If method overriding is...

Method Overriding in Java: Definition, Rules, and Examples

Method Overriding Method Overriding is a process in Java where a subclass provides a specific implementation for a method that is already defined in its superclass. Key Points 1. Method Overriding requires inheritance. 2. To override a method, the subclass method must have the same name, return    type, and parameter list as the superclass method. 3. During method overriding: The subclass method definition is used (exposed). The superclass method definition is hidden. This concept is sometimes referred to as method hiding (though strictly         speaking, method hiding is for static methods). 4. Only instance methods (non-static methods) can be overridden. 5. Method overriding cannot be achieved within the same class; it only works between subclass and superclass. Example class Animal {     void sound() {         System.out.println("Animal makes a sound");     } } class Dog extends Animal {     @Overri...