Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to write class as generic class

Tags:

java

generics

I have class lets say

Class Rectange{
    int height;
    int side;
}

what all are the cases in which I can make this class as generic? How to identify that we want to write a generic class? Probably a practical example will be good.

Update

  1. what are the use cases to make our class generics?

  2. Real life scenarios where we will use generics?

like image 988
eatSleepCode Avatar asked Apr 14 '26 22:04

eatSleepCode


2 Answers

You can make this class generic, if you want any of the mentioned types to be variable.

Currently your class only contains references to the type int. If you want to make this type variable, you can use this code:

class Rectange<T extends Number> {
    T height;
    T side;
}

Afterwards you can then make instances, that either use Integers or other types to store height and side:

class Main {
    public static void main(String[] args) {
        Rectange<Integer> intRect = new Rectange<>();
        intRect.height = 12;
        Integer intHeight = intRect.height; // no cast needed, the height is guaranteed to be an int

        Rectange<Double> dblRect = new Rectange<>();
        dblRect.height = 1.20076;
        Double doubleHeight = dblRect.height; // this time, height is guaranteed to be an double
    }
}

As a conclusion I would say: Use generics, if you have to make the types variable. So using generics can be usefull, depending on your use case.

like image 76
slartidan Avatar answered Apr 17 '26 10:04

slartidan


Real-life example: I need a simple processor which will take many values and return the highest, the lowest and median, based on natural ordering. I don't know which type of objects it will operate (or I do, but don't want to restrict it to using only one particular type), and I don't want it to accept Object to avoid casting. So I make this class and all its methods generic:

public class MySimpleProcessor<T extends Comparable<T>> {

    public void putValue(T value) { /*...*/ }
    public T getHighest()         { /*...*/ }
    public T getLowest()          { /*...*/ }
    public T getMedian()          { /*...*/ }
} 

Now, MySimpleProcessor can operate on any comparable objects:

MySimpleProcessor<String> stringProcessor;             // will accept and return strings
MySimpleProcessor<Integer> intProcessor;               // will accept and return integers
MySimpleProcessor<AnotherComparable> anotherProcessor; // will operate on some other type
like image 20
Alex Salauyou Avatar answered Apr 17 '26 11:04

Alex Salauyou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!