Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - Instantiating objects of type X when all you have is the reference type
    text
    copied!<p>I had a quick look at the "Related Questions" suggested but I couldn't find one directly related to what I'm asking. Even if there was one, I'd still appreciate your opinion on the best way to do this.</p> <p>First some context.<br> I'm working on extending a Java Application and I have the following Interface and Class:</p> <pre><code>public interface Mapper { public void foo(); } public class SomeGrammar implements Mapper { public SomeGrammar() {} public SomeGrammar(SomeGrammar toCopy) { //Copy specific fields } public void foo() {} } </code></pre> <p>The application I'm using was built with only one grammar type in mind, <code>SomeGrammar</code>, and as such the <code>SomeGrammar</code> class is woven throughout through the application. </p> <p><code>SomeGrammar</code> objects are often copied using a copy constructor:</p> <pre><code>SomeGrammar aGrammar = new SomeGrammar(); SomeGrammar newGrammar = new SomeGrammar(aGrammar); </code></pre> <p>I'm attempting to implement new types of grammars. So I was going to pull the core methods out and implement a <code>Grammar</code> interface, or even consolidate those methods into the <code>Mapper</code> interface. So all grammar classes would implement this interface.</p> <hr> <p>Anyway, my question to you is, what is the best way to go about replacing the above line so that I can generalise the copying of whatever grammar object happens to be currently being referenced by the Interface's Type?</p> <p>Obviously I can't</p> <pre><code>Grammar newGrammar = new Grammar(aGrammar); </code></pre> <p>since <code>Grammar</code> is the Interface's Type, and <code>new Grammar(aGrammar)</code> makes no sense. I suppose I could add a cloning method to my interface to use instead of a copy constructor, but as I said before, I'd appreciate your opinion on the matter.</p> <p>Thanks in advance,<br> Eoin</p>
 

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