Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4125078
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T23:49:22+00:00 2026-05-20T23:49:22+00:00

I know quite a bit how to use C++-Templates — not an expert, mind

  • 0

I know quite a bit how to use C++-Templates — not an expert, mind you. With Java Generics (and Scala, for that matter), I have my diffuculties. Maybe, because I try to translate my C++ knowledge to the Java world. I read elsewhere, “they are nothing alike: Java Generics are only syntactic sugar saving casts, C++ Templates are only a glorified Preprocessor” 🙂

I am quite sure, both is a bit simplified a view. So, to understand the big and the subtle differences, I try to start with Specialization:

In C++ I can design a Template (class of function) that acts on any type T that supports my required operations:

template<typename T>
T plus(T a, T b) { return a.add(b); }

This now potentially adds the plus() operation to any type that can add().[note1][1]

Thus, if T supports the add(T) my template woll work. If it doesn’t,
The compiler will not complain as long as I do not use plus(). In Python
we call this “duck typing”: *If it acts like a duck, quacks like a duck,
it is a duck.* (Of course, with using type_traits this is modified a bit,
but as long as we have no concepts, this is how C++ Templates work, right?)

I guess, thats how Generics in Java work as well, isn’t it? The generic type I device is used as a “template” how to operate on any anything I try to put in there, right? As far as I understand I can (or must?) put some constraints on the type arguments: If I want to use add in my template, I have to declare the type argument to implement Addable. Correct? So, no “duck typing” (for better or worse).

Now, in C++ I can choose to specialize on a type that has no add():

template<>
T plus<MyX>(MyX a, MyX b) { return a + b; }

And even if all other types still can use the “default” implementation, now I added a special one for MyX — with no runtime overhead.

Is there any Java Generics mechanism that has the same purpose? Of course, in programming everything is doable, but I mean conceptually, without any tricks and magic?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T23:49:23+00:00Added an answer on May 20, 2026 at 11:49 pm

    No, generics in Java don’t work this way.

    With generics you can’t do anything which would not be possible without Generics – you just avoid to have to write lots of casts, and the compiler ensures that everything is typesafe (as long as you don’t get some warnings or suppress those).

    So, for each type variable you can only call the methods defined in its bounds (no duck typing).

    Also, there is no code generation (apart from some adapter methods to delegate to methods with other parameter types for the purpose of implementing generic types). Assume you had something like this

    /**
     * interface for objects who allow adding some other objects
     */
    interface Addable<T> {
       /** returns the sum of this object and another object. */
       T plus(T summand);
    }
    

    Then we could create our sum method with two arguments:

    public static <T extends Addable<T>> T sum(T first, T second) {
        return first.plus(second);
    }
    

    The static method is compiled to the same bytecode like this (with additional type information in annotations):

    public static Addable sum(Addable first, Addable second) {
        return first.plus(second);
    }
    

    This is called type erasure.

    Now this method can be called for every pair of two elements of an addable type, like this one:

    public class Integer implements Addable<Integer> {
        public Integer plus(Integer that) {
           return new Integer(this.value + that.value);
        }
    
         // private implementation details omitted
    }
    

    What here happens is that the compiler creates an additional synthetic method like this:

    public Object plus(Object that) {
        return this.plus((Integer)that);
    }
    

    This method will only be called by generic code with the right types, this guarantees the compiler, assuming you are not doing some unsafe casts somewhere – then the (Integer) cast here will catch the mistake (and throw a ClassCastException).

    The sum method now always calls the plus method of the first object, there is no way around this. There is not code generated for every type argument possible (this is the key difference between Java generics and C++ templates), so we can’t simply replace one of the generated method with a specialized one.

    Of course, you can create a second sum method like irreputable proposed (with overloading), but this will only be selected if you use the MyX type directly in source code, not when you are calling the sum method from some other generic code which happens to be parametrized with MyX, like this:

    public static <T extends Addable<T>> product (int times, T factor) {
        T result = factor;
        while(n > 1) {
            result = sum(result, factor);
        }
        return result;
    }
    

    Now product(5, new MyX(...)) will call our sum(T,T) method (which in turn calls the plus method), not any overloaded sum(MyX, MyX) method.

    (JDK 7 adds a new dynamic method dispatch mode which allows specialization by every argument on run time, but this is not used by the Java language, only intended to be used by other JVM-based languages.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a bit of a mystery here that I am not quite understanding
I have used R quite a bit and I know I can use head(data[,column])
I know that C++ simplified quite a bit since it was made, and im
I log quite a bit of stuff, and have noticed that Eclipse Console makes
I know I'm not asking this quite right, either. Please help me better form
While I know IronRuby isn't quite ready for the world to use it, I
I haven't really used variance calculation that much, and I don't know quite what
I have bash script that I use regularly in my job to automate a
I have read other related posts, but am still not quite sure how, or
I have written quite a bit of code of the past few years. I've

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.