Thursday, 8 June 2017

Java Tutorial: Generics in java | Java Generics [Wildcard in Java Generics] ~ foundjava


Click here to watch in Youtube :
https://www.youtube.com/watch?v=VawfMZaSWJU&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Generics in java | Java Generics [Wildcard in Java Generics] 
Shape.java
public abstract class Shape
{
    abstract void draw();
}

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

class Rectangle extends Shape
{
    void draw()
    {
        System.out.println("drawing rectangle");
    }
}
GenericDemo.java
import java.util.ArrayList;
import java.util.List;

public class GenericDemo
{

    public static void main(String args[])
    {
        List<Rectangle> recList = new ArrayList<Rectangle>();
        recList.add(new Rectangle());
        recList.add(new Rectangle());
        drawShapes(recList);

        List<Circle> circleList = new ArrayList<Circle>();
        circleList.add(new Circle());
        circleList.add(new Circle());       
        drawShapes(circleList);
    }

    /*
     * This method accepts only the list contains child class of Shape
     */
    public static void drawShapes(List<? extends Shape> shapeList)
    {
        for (Shape shape : shapeList)
        {
            shape.draw();
        }
    }

}
Output
drawing rectangle
drawing rectangle
drawing circle
drawing circle
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment