Results 1 to 10 of 10
  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default The point of existence of Generics

    I have started with this tutorial on Generics. I have sort of understood how their example is working in their Box class example, but I am not clear about what they are trying to say.

    What I understand is that I might have a class A from which two different classes B and C inherit. Then I can have a class Foo, which has a method which takes an A, and another method which returns that A. Then I can have a piece of code which passes in a B (and that's not a problem since B extends A), and expects a B from the other method of Foo. Then I can also have another piece of code which passes in a C, and that will result in Runtime Exception.

    But I wrote the following code. It seems to work, i.e. does not give a runtime exception.

    Java Code:
    public class A {}
    
    
    
    public class B extends A {
    	
    	@Override
    	public String toString() {
    		return "B";
    	}
    }
    
    
    
    public class C extends A {
    	@Override
    	public String toString() {
    		return "C";
    	}
    }
    
    
    
    public class Foo {
    	private A a;
    	
    	void methodThatTakesA(A a) {
    		//Do something with a... In the process, assign a to a field of this class e.g.
    		this.a = a;
    	}
    	
    	
    	A methodThatReturnsA() {
    		//some code
    		return a;
    	}
    
    }
    
    
    
    public class MainClass {
    
    	public static void main(String [] args) {
    		Foo foo = new Foo();
    		passB(foo);
    		
    		passC(foo);
    		
    		//****************************************//
    		
    		A aReturned = foo.methodThatReturnsA();
    		
    		System.out.println(aReturned.toString());
    	}
    	
    	
    	private static void passB(Foo foo) {
    		foo.methodThatTakesA(new B());
    	}
    	
    	
    	private static void passC(Foo foo) {
    		foo.methodThatTakesA(new C());
    	}
    	
    }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: The point of existence of Generics

    Your writeup and example have nothing to do with generics (you are not even using a generic type).

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: The point of existence of Generics

    Your writeup and example have nothing to do with generics (you are not even using a generic type).
    In the tutorial I linked to, there is this following class which is not generic. Its two methods which take and return an object of Object class respectively, so any class' object can be passed to the first of these methods (i.e. set(Object object)), and the same class' object will be returned from the second method. They have said that one part of code might pass in and expect back an Integer. Another part of code might pass a String mistakenly, which will result in a runtime exception.

    Java Code:
    public class Box {
        private Object object;
    
        public void set(Object object) { this.object = object; }
        public Object get() { return object; }
    }
    Then they have presented a generic version of the Box class. They are giving this example to demonstrate the concept of a generic class.

    I understand how the example works, but I am not clear about when exactly does such a scenerio happen? So I thought about it like, there will be class which other classes will extend; and then somewhere some method will take an object of this class, and some other (or the same) method will return that passed-in object. Now one part of the code will pass in and expect back one of the extended classes, and another part of the code will pass in another one of the extended classes - which should give me a runtime exception.

    But when I translated this idea into the code above, I didn't get any exception.

    If I got an exception, then I would naturally proceed to think about how generics solve that problem. But I could not reproduce the problem.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: The point of existence of Generics

    Before generics:
    Java Code:
    // method inside a NonGeneric class
    List methodThatReturnsAList() {...}
    ...
    NonGeneric someObject = ...;
    List aList = someObject.methodThatReturnsAList();
    MyClass entry = (MyClass) aList.get(0);
    MyOtherClass entry2 = (MyOtherClass) aList.get(1);
    There is nothing in there that says that the List is a List of MyClass, and there could be anything in it, hence no compiler error.

    Now:
    Java Code:
    // method inside a Generic<T> class
    List<T> methodThatReturnsAList() {...}
    ...
    NonGeneric<MyClass> someObject = ...;
    List<MyClass> aList = someObject.methodThatReturnsAList();
    MyClass entry = aList.get(0);
    MyOtherClass entry2 = aList.get(1);
    Bang, compiler error.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: The point of existence of Generics

    hence no compiler error.
    and no runtime exception either. :s
    ________________________________________________

    EDIT:

    Actually there are compiler errors on the last two statements: Type mismatch: cannot convert from Object to MyClass and Type mismatch: cannot convert from Object to MyOtherClass

    __________________________________________________ _

    EDIT:

    OK I added casts to those erroneous lines and got a ClassCastException on the second one. I think this is the runtime exception they are talking about in the tutorial.
    Last edited by Zarah; 05-11-2016 at 12:30 PM.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: The point of existence of Generics

    Yes, ClassCast is a runtime exception.

    The whole point behind generics is to allow for compile time checking rather than simply allowing an Object (or some other super class) to be past into something and then hoping it's actually an XYZ object.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,991
    Rep Power
    8

    Default Re: The point of existence of Generics

    Generics are awesome at compile time. Although nothing is stopping you from doing:
    Java Code:
    List<Object> foobar = new ArrayList<>()
    And once you think you understand how to use it, you see lines like this that make your head explode:
    Java Code:
    public static <T extends Comparable<? super T>> T max(Collection<T> coll) { ... }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  8. #8
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: The point of existence of Generics

    The whole point behind generics is to allow for compile time checking rather than simply allowing an Object (or some other super class) to be past into something and then hoping it's actually an XYZ object.
    Thank you so very much, this is the most precise way I have been told this, and I am almost clear about it, except one thing:

    With Collections, I understand that there is no way other than using generics to specify what datatype can a List can contain. So Generics are helping us enforce the use of the exact correct datatype, instead of just hoping that correct datatype will be passed.

    But in the Box example they have given in the tutorial, and about which they have said, "One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error." - why don't they just use the Integer datatype as the argument and return type of the methods of the Box class, instead of using an Object and hoping that nobody will pass in a String/any non-Integer?

  9. #9
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,991
    Rep Power
    8

    Default Re: The point of existence of Generics

    Quote Originally Posted by Zarah View Post
    Thank you so very much, this is the most precise way I have been told this, and I am almost clear about it, except one thing:

    With Collections, I understand that there is no way other than using generics to specify what datatype can a List can contain. So Generics are helping us enforce the use of the exact correct datatype, instead of just hoping that correct datatype will be passed.

    But in the Box example they have given in the tutorial, and about which they have said, "One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error." - why don't they just use the Integer datatype as the argument and return type of the methods of the Box class, instead of using an Object and hoping that nobody will pass in a String/any non-Integer?
    Because if you want to make another Box that contains String, Doubles, or MyObject, you have to create new classes of Box over and over again. With generics you can specify what Box accepts as "content", so you only create one Box class, but that can take different "contents". The Box is generic.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  10. #10
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: The point of existence of Generics

    @Surfman I get it now. Thank you so very much.

Similar Threads

  1. Check the existence of a parameter.
    By Jack_Tauson_Sr in forum New To Java
    Replies: 4
    Last Post: 03-21-2014, 12:11 AM
  2. Replies: 2
    Last Post: 02-05-2013, 03:35 PM
  3. Replies: 1
    Last Post: 08-02-2009, 11:52 AM
  4. Verifying existence of a table in a db
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-14-2008, 09:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •