Java – Instantiating objects of type X when all you have is the reference type


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.

First some context.
I'm working on extending a Java Application and I have the following Interface and Class:

public interface Mapper {
  public void foo();

public class SomeGrammar implements Mapper {

  public SomeGrammar() {}

  public SomeGrammar(SomeGrammar toCopy) {
    //Copy specific fields

  public void foo() {}

The application I'm using was built with only one grammar type in mind, SomeGrammar, and as such the SomeGrammar class is woven throughout through the application.

SomeGrammar objects are often copied using a copy constructor:

SomeGrammar aGrammar = new SomeGrammar();
SomeGrammar newGrammar = new SomeGrammar(aGrammar);

I'm attempting to implement new types of grammars. So I was going to pull the core methods out and implement a Grammar interface, or even consolidate those methods into the Mapper interface. So all grammar classes would implement this interface.

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?

Obviously I can't

Grammar newGrammar = new Grammar(aGrammar);

since Grammar is the Interface's Type, and new Grammar(aGrammar) 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.

Thanks in advance,

Best Solution

If I understood your question correctly, my solution would look something like the following :

Lets say we had 3 concrete grammars we wished to create, GrammarA, GrammarB, and GrammarC. We would define each of those classes to implement the Grammar interface. The GrammarInterface would have your foo() function, and also a doCopy() function defined. Each of those concrete Grammar classes would then be responsible for implementing the foo() capability and for returning a copy of themselves by calling a copy constructor. Is this what you were looking for?

interface IGrammar { 

    public void foo();
    public Grammar doCopy();


class GrammarA implements IGrammar { 

    public Grammar doCopy(Grammar g) { 

        return new GrammarA(g);