What is the point of creating a class?

when you have a method, I understand that it makes sense to declare it general so that I can accept general arguments. Like this:

public <T> void function(T element) {
    // Some code...
}

But what is the idea of ​​creating an entire class if I can just declare each generic method?

+5
source share
4 answers

Well, the difference is that if you try to make each method of its kind a universal type of the general type that you use in your firstGenericMethod, it may or may not be the same type. What I mean.

public <T> void firstGenMethod(...){

}

public <T> void secondGenMethod(...){

}

Test:

  SomeClass ref = new SomeClass();
  ref.firstGenMethod("string");
  ref.secondGenMethod(123);//legal as this generic type is not related to the generic type which is used by firstGenMethod

In the above case there is no gaurentee that both methods have the same common type. It depends on how you call them. However, if you create a generic class, this type applies to all methods inside this class.

class Test<T>{

    public void firstGenMethod(T t){

    }

    public  void secondGenMethod(T t){

    }
}

Test:

 Test<String> testingString = new Test<>();
   testingString.firstGenMethod("abc");
   testingString.firstGenMethod(123);// invalid as your Test class only expects String in this case

, , () . - Java Collection Framework

+6

Collection. List<T> . , , ? , ArrayList.get(i)?

+4

, .

"". , , , , .. .

, , (, , ...) .

, "" , , ... ( .)

+2

- / . Generics .
, . - , , -, , , .., , , , .

, , , .
oracle docs
- ,

public class Box {
    private Object object;

    public void set(Object object) { this.object = object; }
    public Object get() { return object; }
}



public class Box<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}


I also suggest you see this tutorial

+1
source

All Articles