• How to handle similar classes with nested classes in JAVA

    SapnaVishwas Member

    How to handle similar classes with nested classes in JAVA

  • Ganesh Member

    Well you still haven’t revealed how you plan to instantiate the two classes (identical constructors? or different ones?)

    Anyway, now it’s easier to understand.

    If you have to stick with the class names then you can (and should!) un-nest the identical classes and keep the UserCredentials classes nested deep.

    I don’t have experience with JSON annotation but there are nice tutorials that point you to the proper direction.

    The following link is not about annotations but shows you how json classes should be implemented:
    http://www.tutorialspoint.com/json/json_java_example.htm

    The following uses XML annotations:
    http://stackoverflow.com/questions/11001458/json-java-object-to-json

    And there are many more.

    So instantiating is, likely, you invoke the deserializer of your choice with a JSON string… or create the object manually, whichever you like.
    If you need some behaviour that works both with host (having UserNamePassword) and guest (having FirstLastNameEmail) then you have to interface them. Something like:

    public interface UCInterface {
      void setCred(String s1, String s2, String s3);
      Object getCred();
    }
    
    public class UserCredentials implements UCInterface {
      ...
    
      public void setCred(String s1, String s2, String s3) {
        UserNamePassword.UserName = s1;
        UserNamePassword.Password = s1;
        UserNamePassword.PasswordEncryptionType = Integer.parseInt(s3);
      }
      public Object getCred() {
        return UserNamePassword;
      }
    }

    Similar for Guest (but you don’t even need parseInt here)
    Note that I haven’t tested, not even compiled the code above so it may bleed for several wounds but may give you an idea…

    Thereafter, whenever you want to manipulate that object, be it host or guest, you can invoke setCred and getCred, accordingly.

  • Abhey Member

    Sounds pretty obscure but derivation may work. However A:B and AA:B are not the same and the two C’s aren’t the same either.

    Have the two B’s implement the same interface that contains one or two initialization functions. Is it something you are looking for?

    The hardcore way is to exploit reflection but hard to tell more from this skeleton.

Viewing 2 reply threads
  • You must be logged in to reply to this topic.
en_USEnglish