Ads

Sunday, December 27, 2020

A class has an integer data member 'i' and a method named 'printNum()' to print the value of 'i'. Its subclass also has an integer data member 'j' and a method named "printNum()" to print the value of "j". Make an object of the subclass and use it to assign a value to "i" and to "j". Now call the method "printNum()" by this object.

Here's the program to solve the problem as described:

Source Code..

class A {

    int i;

    public void printNum() {

        System.out.println("Value of i: " + i);

    }

}

 

class B extends A {

    int j;  

    public void printNum() {

        System.out.println("Value of j: " + j);

    }

}

public class Main {

    public static void main(String[] args) {

        B obj = new B();

        obj.i = 10;

        obj.j = 20;

        obj.printNum();  // will print value of j

    }

}

 Code Explanation:

In this code, we have a superclass ‘A’ with an integer data member ‘I’ and a method printNum() that prints the value of’‘I’. We also have a subclass ‘B’ that extends A and has an additional integer data member ‘j’ and a method printNum() that prints the value o f j’.

 

In the main() method, we create an object of the subclass ‘B’ and assign values to both ‘I’ and ‘j’. Finally, we call the printNum() method using the object obj, which is of type ‘B’. Since printNum() is overridden in ‘B’, it will print the value of ‘j’ instead of ‘I’. 


The given code is an example of inheritance in object-oriented programming. It consists of a base class "Parent" and a derived class "Child". The Parent class has an integer data member "i" and a method named "printNum()" to print the value of "i". The Child class is inherited from the Parent class and has an integer data member "j" and a method named "printNum()" to print the value of "j".

 

In the main method, an object of the Child class is created and used to assign values to both "i" and "j". Then, the "printNum()" method is called by the same object to print the values of "i" and "j".

 

This code makes use of inheritance, which is a fundamental concept in object-oriented programming. Inheritance allows a new class to be based on an existing class, inheriting its attributes and behaviors. In this case, the Child class inherits the data member and method of the Parent class. It also uses polymorphism, which allows objects of the same class hierarchy to behave differently based on the context in which they are used. In this example, the Child class overrides the "printNum()" method of the Parent class to print the value of "j" instead of "i".

 


No comments:

Post a Comment