mercredi 19 avril 2017

2 Java classes with the same Content (functions, variables etc.)

Say that the user gives you a phone number (as an object of the class PhoneNumber or a subclass of it) which he first states if it's a Mobile Phone or a House Phone. In the main program you should be able to know (way afterwards) if it refers to a Mobile Phone or to a House Phone.

And here's what you can't do:

  1. You can't check the numbers to find out because the user is actually able to give any number he wants (he could give 9123 for a House Phone).
  2. You can't make any variable (in the classes or in the main Program) that states the answer.

Should you make two different classes that extend the class PhoneNumber and have the exact same content (in my example they are actually empty, but in my real problem they're not)? If you do so you can make objects of those classes and use instanceof in the main program, but I wonder if there's another solution, one that seems better to the eye.

Example:

public class PhoneNumber{
     private int Number;

     public PhoneNumber(int Number){
          this.Number = Number;
     }
}

public class Mobile extends PhoneNumber{}

public class HousePhone extends PhoneNumber{}






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire