Note that there are some explanatory texts on larger screens.

plurals
  1. PODistinguish instances of objects implementing an interface, by an enum value or by its implementing interface
    primarykey
    data
    text
    <p>The situation is that i have this interface:</p> <pre><code>interface ISymbol { } </code></pre> <p>and these classes:</p> <pre><code>class Letter implements ISymbol { } class Number implements ISymbol { } class LowerCaseLetter extends Letter { } class UpperCaseLetter extends Letter { } </code></pre> <p>Now lets say that i have this function, in a different class. The logic that this class performs DOES NOT belong in the implementation of the ISymbol classes:</p> <pre><code>class SymbolMonitor { void func(ISymbol[] symbols) { for (ISymbol iSymbol : symbols) { // If the symbol is a number // or a lower case letter do something. } } } </code></pre> <p>But i don't want to check for those two types specifically because i might have other implementing classes of ISymbol that will also require the same logic.</p> <p>My question is about the preferred way of action. I have two solutions to the problem. 1. Create an like so:</p> <pre><code>enum SymbolType { NORMAL, SPECIAL1, SPECIAL2, } </code></pre> <p>and add to the code:</p> <pre><code> interface ISymbol { SymbolType getType(); } class SymbolMonitor { void func(ISymbol[] symbols) { for (ISymbol iSymbol : symbols) { if(iSymbol.getType().equals(SymbolType.SPECIAL1)) { // Do special1 logic } if(iSymbol.getType().equals(SymbolType.SPECIAL2)) { // Do special2 logic } } } } </code></pre> <ol> <li><p>I can create empty interfaces and use the instanceof function. </p> <pre><code>interface ISpecialSymbol1 </code></pre> <p>{</p> <p>}</p> <p>interface ISpecialSymbol2 {</p> <p>}</p> <p>class LowerCaseLetter extends Letter implements ISpecialSymbol1 {</p> <p>}</p> <p>class Number implements ISymbol, ISpecialSymbol1 {</p> <p>}</p></li> </ol> <p>so that the function will be:</p> <pre><code>class SymbolMonitor { void func(ISymbol[] symbols) { for (ISymbol iSymbol : symbols) { if(iSymbol instanceof ISpecialSymbol1) { // Do special 1 logic. } if(iSymbol instanceof ISpecialSymbol2) { // Do special 2 logic. } } } } </code></pre> <p>I think that the second option is much more simpler, but I am new to java and I am not sure at all what is the correct way of action to use.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload