3

My project consists of two classes: type 1 and type 2 is that each has its own functions and fields I'm gonna use them as follows:

private void initialize(String type) {
    if (type == "Type1") {
      x = new Type1;
    } else if (type == "Type2") {
      x = new Type2;
    }
}

What type of X variable must be ?

<Update 1>=============================

I use superclass and interface but I do not have access to variables and methods of type1 or type2 and only have access to variables and methods of the superclass

<Update 2>=============================

  public class Type1 extends SuperClass{
    public int var = 1;
  }

  public class Type2 extends SuperClass{
    public int var = 2;
  }

  private void initialize(String type) {
    switch (type) {
      case "Type1":
        x = new Type1();
        break;
      case "Type2":
        x = new Type2();
        break;
    }
  }

  void main(){
    //int num = x.var;
  }

In this case can not be used to cast : ((Type1)x).var

Delay
  • 93
  • 3
  • 9

6 Answers6

2

Use an interface which will be implemented by both classes

public interface Typeimplemntor{}
public class Type1 implements Typeimplemntor{}
public class Type2 implements Typeimplemntor{}

After that in your function

 private void initialize(String type) {
Typeimplemntor typImp;
        if (type == "Type1") {
          typImp = new Type1();
        } else if (type == "Type2") {
          typImp = new Type2();
        }
      }

Complete example for update

    public class Test {
        public static void main (String argd[])
        {
            String type= "Type2";
            Typeimplemntor typeimplemntor = null;
            if (type.equals("Type1")) {
                typeimplemntor = new Type1();
            }else if (type.equals("Type2")) {
                typeimplemntor = new Type2();
            }

            typeimplemntor.print();
            if (typeimplemntor instanceof Type1) {
                int y = ((Type1)typeimplemntor).x;
                System.out.println(y);
                ((Type1)typeimplemntor).notInInterfaceType1();
            }else if (typeimplemntor instanceof Type2){
                int y = ((Type2)typeimplemntor).x;
                System.out.println(y);
                ((Type2)typeimplemntor).notInInterfaceType2();
            }


        }
    }

public class Type1 implements Typeimplemntor {
    int x = 5;
    public void print () {
        System.out.println("Printed from Type1");
    }
   public void notInInterfaceType1 () {
    System.out.println("Not in interface but in Type1");
   }
}

public class Type2 implements Typeimplemntor {
    int x = 15;
    public void print () {
        System.out.println("Printed from Type2");
    }
    public void notInInterfaceType2 () {
       System.out.println("Not in interface but in Type2");
    }
}

public interface Typeimplemntor {
    void print();
}

If you have method which will be used in both the classes you can define them in interface and they can be accessed directly according to their implementation in classes. If there are some other methods or variables then you have to check the instance and then you have cast into the same.

Mandeep Singh
  • 1,287
  • 14
  • 34
  • defining an interface is certainly the right way! (see factory pattern or other creational pattern for deeper knowledge) – Martin Frank Oct 20 '16 at 05:43
1

if x is a variable that can hold both Type1 and Type2 then x could be:

  1. a superclass of both
  2. an interface that both classes are implementing

Example

Case 1

public class SuperType{}
public class Type1 extends SuperType{}
public class Type2 extends SuperType{}

then you can do

private void initialize(String type) {
    SuperType x = new Type1();
      //or
    SuperType x = new Type2();

  both are valid 

Case 2

public interface IType{}
public class Type1 implements IType{}
public class Type2 implements IType{}

then you can do

private void initialize(String type) {
    IType x = new Type1();
      //or
    IType x = new Type2();

Edit

In both cases 1 and 2 x is a variable that can only invoke methods from Supertype or IType maybe you need Type1 specific methods then a casting is required

((Type1)x).myType1OnlyMethod ();
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    both ways are correct but having the OO principles in mind you should prefer an interface over inheritance... – Martin Frank Oct 20 '16 at 05:45
  • I use this way(superclass and interface) but I do not have access to variables and methods of type1 or type2 and only have access to variables and methods of the super class(type) – Delay Oct 20 '16 at 05:48
  • A... very simple... you need to cast the variable x to the type class you need.. I will update the answer – ΦXocę 웃 Пepeúpa ツ Oct 20 '16 at 05:58
  • The main problem is that should be cast There is no other way except the cast? – Delay Oct 20 '16 at 06:19
1

Do it like this

    If (Type instanceOf Type1) {
                                x = new Type1;
                              } 
   else if (Type instanceOf Type2)   {
                                x = new Type2;
                               }
puneet yadav
  • 107
  • 4
0

If you want x to accept an instance of either Type1 or Type2, it must be some common ancestor or interface they both share. If you haven't declared such a type, you can always resort to Object, which is the common ancestor of all classes.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • In this way the need to cast off, if I do not know which classes to be put in x ,So how do I cast the variable x ? The value of x is dependent on the String type – Delay Oct 21 '16 at 05:42
  • In this way the need to cast , I do not know which classes to be put in x ,So how do I cast the variable x ? The value of x is dependent on the String type – Delay Oct 21 '16 at 05:43
0

If you're defining a new object, it would have to be:

Type1 x = new Type1;
Type2 y = new Type2;

And then the constructor in those two classes will create that new object

If you are asking about inheritance, then it's a similar answer. You want to have your superclass (the class which gives some baseline variables that subclasses will have) and then you want to extend it to your two types. Roughly, it will look like this.

public class Type{
    private String exampleVariable;
    ...
}

public class Type1 extends Type{
    ...
}

public class Type2 extends Type{
    ...
}

And then you could create object via

Type a = new Type1();
Type b = new Type2();
0

Just making a point, as long as you have control of modifying and writing Type1 and Type2, creating common interfaces should be fine.

However if you are making use of external classes where you do not have control of the source code, I'd suggest making use of Object reference.

Regardless ensure that you are aware of all the methods available in the classes and add appropriate type safety/casting feature wherever applicable.

Kamal Kunjapur
  • 8,547
  • 2
  • 22
  • 32