Menu
Topics Index
...
`

Generics Lower Bounded Wildcard


If you need explanation Read this topic

If you need Answer Take test on this topic

Generics Lower Bounded Wildcard
What will be the output of the following program?
public class GenericsLowerBoundedWildCardDemo1 {
    public static void main(String args[]) {
        PrintClassNameHelper<Rectangle> rectangleClass = new PrintClassNameHelper<Rectangle>(new Rectangle());
        print(rectangleClass);
    }
    
    static void print(PrintClassNameHelper<? super Rectangle> printName) {
        printName.print();
    }
}
class Shape {
    void printName() {
        System.out.println("This is shape class");
    }
}

class Rectangle extends Shape {
    void printName() {
        System.out.println("This is Rectangle class");
    }
}
class Square extends Rectangle {
    void printName() {
        System.out.println("This is Square class");
    }
}
class PrintClassNameHelper<T extends Shape> {
    T shape;
    PrintClassNameHelper(T shape) {
        this.shape = shape;
    }
    void print() {
        shape.printName();
    }
}

A. This is shape class
B. This is Rectangle class
C. This is Square class
D. Compilation Error
E. Runtime Error
Topic: Generics Wildcards In Java With Examples

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is B...here we have Shape class which is Parent class to the Rect and Square...class PrintClassNameHelper which is able to receive the Objects of Child class of Shape...

Coming to the main class we create Object to the PrintClassNameHelper with Object of Rect and calling the print() in the main class...here we use the lower bound concept to restrct the supertype...here super rect means it wil accept supertypes of rectangle....

from these method we are calling the print method of PrintClassNameHelper..from there we are calling  the printName() with the object of rectangle so that method in Rectagle class wil called and print this is Rectangle class

Posted by Uday Kumar    2014-11-06 13:28:23


ans b. in main object for the rectangle class is created with printClassnameHelper class, it extends shape class.thn print() method called with created object as an argument.here super keyword used  witg rectangle class.frm this ptintClassNameHelper initialize shape with rectangle.so in void print(),rectangle. printName() function called and sop prints " this is rectangle class"

Posted by Maheshwari Natarajan    2014-11-07 02:44:52


This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Maheshwari Natarajan. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-11-07 04:30:16


© meritcampus 2019

All Rights Reserved.

Open In App