Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: Generics Date: Wed, 17 Aug 2016 15:22:10 -0400 Organization: A noiseless patient Spider Lines: 63 Message-ID: References: <681a67de-8a78-46ab-a028-5176a48df402@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 17 Aug 2016 19:22:24 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="22e5ab429c5a4bb738666b9c52e40d69"; logging-data="30712"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18uX24SOq9vo63n3I7XrfDW" User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Thunderbird/45.2.0 In-Reply-To: <681a67de-8a78-46ab-a028-5176a48df402@googlegroups.com> Cancel-Lock: sha1:GszqIse4nNJ+xxzpu70TtDQU8uU= Xref: csiph.com comp.lang.java.programmer:35380 On 8/17/2016 2:59 PM, Eric Douglas wrote: > Say we have 3 classes. > > public class TestA { > } > > public abstract class TestB { > } > > public class TestC extends TestB { > } > > Now we create an instance. > > TestA testMe = new TestA(); TestA testMe = new TestA(); or, more briefly, TestA testMe = new TestA<>(); > Now within class TestA how do we tell it instance testMe is referencing TestC? > The only thing I could find is to add a method or constructor which passes in a reference to TestC.class or the class name, so there's that for last resort, but I do want to make sure if I have to pass it in separately that it matches the value of E. I'm not sure what you're asking, so I'll try answers to two different questions -- if neither is helpful, please post again. 1) The methods and fields and whatnot within TestA should traffic in things of type "E", like public class TestA { private final E theTest; public TestA(E theTest) { this.theTest = theTest; } public E getTheTest() { return theTest; } // ... } 2) If some code inside TestA needs to be aware of the TestC-ness of some reference or other, use "instanceof": public class TestA { private boolean isItTestC(E thing) { return thing instanceof TestC; } } However, I'd view this need with suspicion. The "instanceof" operator (and its reflective counterparts) are often signs that the design should be reconsidered -- and perhaps retained, but only after due thought has lowered the raised eyebrows. More commonly, it's a sign that polymorphism is not being used to best advantage. -- esosman@comcast-dot-net.invalid The Tooth Fairy has gone high-tech, now pays in Bitecoin.