Inheritance/Overriding question

Morning :)
Here is my situation. I have the following situation, within the same package
Class C, with a protected method doStuff(int x), and a public startStuff() method. This startStuff method calls the doStuff method.
Class IC, which extends C, which also has a separate protected doStuff(int x) method, and a public startStuff() method
I am instantiating an object of class IC, and calling the startStuff method, which first calls super.startStuff(), which in turn (in my mind) should call the doStuff method within Class C, but it isn't. In the stack trace, I can see Class C.startStuff being called, but when it gets to the doStuff method, it invokes the one in class IC, which isn't what I want.
Any way for me to fix this, or am I going about it all wrong?

I think you are talking about something like this :
public class SuperClass
     protected void doStuff()
          System.out.println("doStuff in SuperClass");
     public void startStuff()
          System.out.println("startStuff in SuperClass");
          doStuff();
public class SubClass extends SuperClass
     protected void doStuff()
          System.out.println("doStuff in SubClass");
     public void startStuff()
         super.startStuff();
          System.out.println("startStuff in SubClass");
     public static void main(String args[])
          SubClass aSubClass=new SubClass();
          System.out.println("This is main ");
          aSubClass.startStuff();          
}What is happening here (why doStuff() in SubClass is getting invoked)is as follows:
We invoke any method on a target reference(i.e.aSubClass.startStuff()),the invoked method has a reference to the target object so that it may refer to the invoking(or target )object during the execution of the program.That reference is represented by this.
In method overriding the instance method is chosen according to the runtime class of the object referred to by this.So during the execution of statrStuff() in SuperClass , the doStuff() is invoked on the this reference that is the actual run time type of the target object i.e. SubClass.
That's why doStuff() in SubClass is getting invoked.
If you want to invoke SuperClass.doStuff(),declare doStuff() as class method (Static) in both the classes.The class methods are not invoked by the runtime class of the object,because these are not related with any instance od a class.

Similar Messages

  • Override Question

    this is my code.
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class TextEncryptor implements Encryption, Cloneable, Serializable {
         String encryptedFileName;
         String userText;
         boolean successfulEncryptionPerformed = false;
         KeyGenerator kg;
         SecretKey skey;
         SecretKeyFactory skf;
         DESKeySpec dks;
         Cipher c;
         CipherOutputStream cos;
         PrintWriter pw;
         public TextEncryptor(String encryptedFileName, String userText) {
              this.encryptedFileName = encryptedFileName;
              this.userText = userText;
         public void generateSecretKey() {
            try {
              kg = KeyGenerator.getInstance("DES");
              kg.init(new SecureRandom());
              skey = kg.generateKey();
              skf = SecretKeyFactory.getInstance("DES");
            }catch(Exception e) {
              e.printStackTrace();
         public void initialiseCipher() {
            try {
              Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
              dks = (DESKeySpec)skf.getKeySpec(skey, spec);
              c = Cipher.getInstance("DES/CFB8/NoPadding");
              c.init(Cipher.ENCRYPT_MODE, skey);          
            }catch(Exception e) {
              e.printStackTrace();
         public boolean performEncryption() {
            try {
              cos = new CipherOutputStream(new FileOutputStream(encryptedFileName), c);
              pw = new PrintWriter(new OutputStreamWriter(cos));
              pw.println(userText);
              pw.close();
              successfulEncryptionPerformed = true;
            }catch(Exception e) {
              e.printStackTrace();
              return successfulEncryptionPerformed;
         public DESKeySpec getDESKeySpec() {     
              return dks;     
         public Cipher getIV() {
              return c;
         public boolean equals(Object o) {
              if(o == null) {
                   return false;
              TextEncryptor te;
              try {
                   te = (TextEncryptor) o;
              }catch(ClassCastException cce) {
                   return false;
              return (encryptedFileName.equals(te.encryptedFileName)) && (userText.equals(te.userText));
    }My question is since the only two variables that can be set (in th constructor) are encryptedFileName and userText, do i need to override the clone() method, as these two variables are immutable(strings), but what about the other variables, these are always set to the same values in the methods listed above.please help,
    thanks

    My question is since the only two variables that can be set (in th constructor) are encryptedFileName and
    userText, do i need to override the clone() method, as these two variables are immutable(strings), but
    what about the other variables, these are always set to the same values in the methods listed above.please
    help,
    thanksWell, if you implement Cloneable, then you really should implement clone(), otherwise it doesn't make much sense. Even if you do implement it just as
    public Object clone() {
        return super.clone();
    }

  • Inheritance constructor question

    Hi
    I am having trouble understanding how the superclasses constructor works in inheritance:
    Please look at the following code:
    public class mySuperClass
         mySuperClass ()
              System.out.println("super1");
    public class myClass extends mySuperClass
         myClass ()
              System.out.println("hello1");
         myClass (int q)
              System.out.println("hello2");
    public static void main(String[] args)
              myClass o = new myClass ();
              myClass o = new myClass (3);
    When I run this program the console results are:
    super1
    hello1
    super1
    hello2
    Why does the constructor of the super class run even when I overload it?
    Thanks
    Aharon

    I think you meant to write "Why does the constructor of the super class run even when I overrideit?"
    And the point is you can't override a constructor (technically, they are not even methods). A constructor in a derived class (MyClass) must call a constructor in its superclass (MySuperClass ). If you do not explicitly call one:
    MyClass (int q) {
        super(...arguments...); // <---
        System.out.println("hello2");
    }There will be an attempt to implicitly to invoke super();

  • Inheritance architecture question

    Hello,
    I've an architecture question.
    We have different types of users in our system, normal users, company "users", and some others.
    In theory they all extend the normal user. But I've read alot about performance issues using join based inheritance mapping.
    How would you suggest to design this?
    Expected are around 15k normal users, a few hundred company users, and even a few hundred of each other user type.
    Inheritance mapping? Which type?
    No inheritance and append all attributes to one class (and leave these not used by the user-type null)?
    Other ways?
    thanks
    Dirk

    sorry dude, but there is only one way you are going to answer your question: research it. And that means try it out. Create a simple prototype setup where you have your inheritance structure and generate 15k of user data in it - then see what the performance is like with some simple test cases. Your prototype could be promoted to be the basis of the end product if the results or satisfying. If you know what you are doing this should only be a couple of hours of work - very much worth your time because it is going to potentially save you many refactoring hours later on.
    You may also want to experiment with different persistence providers by the way (Hibernate, Toplink, Eclipselink, etc.) - each have their own way to implement the same spec, it may well be that one is more optimal than the other for your specific problem domain.
    Remember: you are looking for a solution where the performance is acceptable - don't waste your time trying to find the solution that has the BEST performance.

  • FORMCALC (or JS) Default date today with user override questions

    I have a date field where if null, I want today to be inserted. If the user overrides the today date and saves the form, I want the user entered date to stay.
    What I have in FORMCALC is:
    if ($.isNull)
    then
    $.rawValue = num2date(date(), DateFmt(2))
    endif
    The first part works, it populates with today, and I can overrided the date. When I save and then reopen the form, the date is "0".
    Any ideas here?

    I'm having the same problem as described above but I am using JavaScript to reflect the current date:
    var msNow = (new Date()).getTime();
    var d1 = new Date(msNow);
    this.rawValue = util.printd("mm/dd/yyyy", d1);
    The user can override the current date and save the form, BUT when the form is reopened it will run again and insert the current date over the user entered date.
    (I've tried several variations of "if (this.isNull)" to the above code which results in "01/00/0000" when opening the saved form --so it still doesn't retain the date entered by the user.)
    Does anyone know what code I need to add to to keep the user entered date that was saved with the form? Or if there is a better way to make the date calendar default to today, allow user override and save that user entered date on the form?

  • Inheritance related question

    class a{
         public void meth()
              System.out.println("In a");
    class b extends a{
         public void meth()
              System.out.println("In b");
    public class Test extends b{
         public static void main(String[]a)
    }can i call the a's meth() from Test without creating an instance of a? This might be a simple question and i think i cant create it, but if this is possible please tell me how to do it. also im not referring to runtime polymorphism. without using runtime polymorphism, can i access a's meth()? i know by calling super.meth() in b's meth() will solve it but i do not want to go that way.
    Thanks in advance,
    Geet

    meth is not a static method of the class a, so you can't really call it without instantiating class a.
    If you meant "can I call method meth in class a with an instance of class b?",(note that an instance of b is an instance of a) the answer is no as well, because your method from class b has overridden it... Note that you CAN call the method from class a from within class b (but not from Test), by using the keyword super.

  • UIComponent override question

    within my custom UIComponent when I want to addchildren, should I always be overriding and using the
    protected function createChildren ?
    I notice I can use addChild anywhere without overriding the protected createChildren function and it still works.
    Should I not be doing this ?
    Thanks

    It depends on what purpose you are trying to addChild().
    If you are doing that initially while creating the component only then it's better to use createChildren() function, but id you are tring to add child for displayng some data, say like list components or so, then try to use updateDisplayList() method.
    cause, as far as I know, createChildren() method gets called when the component it self is added to display list, that is only single time, and updateDisplayList() gets called whenever th component needs to get updated.
    Hope, this should help u

  • Button Override Question Encore CS5

    Hey everyone.
    I have added chapter points to a single timeline and then linked these chapter points to corresponding menu buttons. These chapters will be viewed via the Chapter Selection menu.  After a chapter has been watched, I want the user to be returned to the Chapter Selection menu. So, I set the Override for the menu buttons to return to the menu.
    But, this does not work
    SO ...
    How do you create Chapters in a single timeline and have the user return to the Chapter Selection menu once the chapter has been viewed?
    thanks

    I did not look a second time, but if you did what you said, it should work. But overrides can be tricky.
    However, the current two methods most recommended (for DVD, the first does not work on bluray) is
    1) to create a single chapter, chapter playlist for each chapter, with an end action on each chapter playlist to return to the menu.
    or
    2) make each chapter its own asset (from Premiere), and its own timeline. Then each chapter is a timeline (and the timeline end action is to the menu), and you make a playlist (not a chapter playlist) for the play all.
    Their are no overrides and no end actions on chapters.

  • Inheritance/Overloading Question

    Hi,
    Can someone please explain why the following piece of code would fail to compile:
    class A
      void m1(int a)    { System.out.println("A"); }
    class B extends A
      void m1(double b) { System.out.println("B"); }
    class C extends B
      void m1(float c)  { System.out.println("C"); }
    class D
      public static void main (String[] args) {
        int i=10;
        C c = new C();
        c.m1(i);
    D.java:28: reference to m1 is ambiguous, both method m1(int) in A and method m1(float) in C match
    c.m1(i);
    From my understanding, B overloads the method m1 of A, and C did likewise. And when C extends B, it inherits the version of m1 in A and B. So C should have 3 versions of m1 available to it, just like this code:
    class C
      void m1(int a)    { System.out.println("A"); }
      void m1(double b) { System.out.println("B"); }
      void m1(float c)  { System.out.println("C"); }
    }Why then the compiler could not decide which method to invoke ? Another strange thing is that if the version of m1 of A and C where to be interchanged, the compiler will not complain.
    Thanks.

    The behaviour of the compiler is correct according to the JLS (par 15.12.2.2). The problem is that there is no most specific method. You need to know that the type of the class in which the method declaration occurs plays a role just as much as the type of the parameters when choosing the most specific method.
    Let us look at the specific case. I will discard the method in class B because it does not affect the result. Thus, we have two choices:
    1) A.m1(int) is not more specific than C.m1(float) because A cannot be converted to C by method invocation conversion.
    2) C.m1(float) is not more specific than A.m1(int) because float cannot be converted to int by method invocation conversion.
    (Look in par 5.3 for the precise definition of method invocation conversion. However, it is pretty straight forward what it means.)
    Thus, neither A.m1(int) nor C.m1(float) is more specific and therefore any call to C.m1 will be ambigious.

  • Inheritance/Abstraction question

    Ok here is what I currently have. I have a base class, ORDERFROM, which I have made abstract. Then I have an interface, ORDERFORM_ACTIONS, whcih defines actions for an order form. Then I have a class ORDERFORM1. Is there a way to add some more abstraction to my order form family tree so I can have default methods with no parmeters? I am looking for a way to keep from having to implement all non parameter methods again for every new order form. I know they have to be implented in the base class for this to happen but what if the location changes? Keep in mind the location of the data items on the order from will change from revision to revision. Here is what the code structure looks like
    public interface OrderFormActions{
       public boolean placeOrder();
       public String getName();
       public String getPhone();
    public abstract class OrderForm implements  OrderFormActions{
      public OrderForm(){
      public String getName(int row, int col){
          String name = getCell(row, col);
      public String getPhone(int row, int col){
          String phone = getCell(row,col);
      public boolean placeOrder(){
    public class OrderForm1 extends OrderForm{
      public OrderFrom1(){
         super();
      public String getName(){
        int row = 1;
        int col =  2;
        return super.getName(row,col);    // I know super is not needed used for illistration
      public String getPhone(){
        int row = 4;
        int col = 12;
        return super.getPhone(row, col);  // I know super is not needed used for illistration
    }Ideas? As abstract as you can go?

    I mean the interface methods have to implented in
    some class. And if I don't want have to implement
    all the interface methods in every inherited class
    then I have will have to implement them in thebase
    class. (Low cuppeling, high conhesiveness)Then, either you should not have an inerface with
    th all those methods, or you should have an adapterThats totally wrong. Parent classes behavior is not governed by the sub classes. refer to Dependency Inversion Principle
    http://www.eventhelix.com/RealtimeMantra/Object_Oriented/dependency_inversion_principle.htm
    class that provides default behaviour from where
    your classes can inherit or you should put those
    default behaviour up in the class hierachy.Now thats an even worse advice. Under what conditions would you provide an adapter. This particular scenario is not one of them. refer to Software open closed principle.
    >
    May the code be with you.If you do things like this I guess the code would not be with you.

  • Inheritance usage question

    I have 2 classes, DBContainerGraphic and DBGraphic. The DBGraphic class has a static method called Create() which creates and returns a DBGraphic object. The DBContainerGraphic extends DBGraphic. DBContainerGraphic also uses a static factory method.
    Now, DBContainerGraphic is inheriting the static method from DBGraphic that instantiates and returns a DBGraphic. [note: it does have a different signature] This create method does not make sense in the context of DBContainerGraphic.
    It will work, but it is not returning a DBContainerGraphic, and thus I feel it should not be exposed on the DBContainerGraphic class.
    What should I do about this? Just ignore it? After all, it is only package scope.

    class DBGraphic
      static DBGraphic makeGraphic() { return new DBGraphic(); }
    class DBContainerGraphic
    extends DBGraphic
      static DBContainerGraphic makeContainerGraphic() { return new DBContainerGraphic(); }
      static DBGraphic makeGraphic() { return new DBContainerGraphic(); }
    }That is almost certainly NOT what you should do though. Instead of refactoring the whole set of classes, in effect introducing some zillion possible bugs, just use the existing classes and then change them slowly over time.
    The advantage of using the existing classes, is that you are finished the project as soon as you start, like right away.
    Andrew

  • Inheritance & Sorting Question

    Hi guys,
    I have created an abstract class Element and then three subclasses; Person, Sportsman and Date. The Person class has the fields such as name, surname, DOB ... The Sportsman class is extended Person class with some more fields and Date naturally has days, months and years. My task is to write a class Sort, which contains a few sorting methods (i.e. quicksort) and is able to sort any Element object.
    My original idea was to create an abstract method sort. For that method to work, I have to consider three parameters; an instance field the sort will be performed on, a type of sorting algorithm to use and an order of sorting (ascending/descending). The problem I stumbled upon is how to tell the method which instance variable to use; it could be done with a switch statement, but it seems so rough and, well, ugly.
    So I'm just wondering if there is a simpler way to do this. Also, if you have a better idea on how to get started with this, please let me know. (I'm not asking for the code, just for the opinion).
    Thanks,
    Ted

    Thank you both for a quick response.
    However, I forgot to mention that the sorting should be done without any help of Java library. Also, the main problem I have seems to be on how to "tell" a method which instance field I have chosen.
    Example:
    Suppose sort(Element e) is an abstract method. I want to sort all the given surnames in the class Person using quicksort in descending order. The method I had in mind should be something like this:
    sort(Element, String, int, int)and the call for the metod with the given arguments would be:
    sort(e, surname, 1, -1) {
       Person p;
       if (e instanceof Person) {
          p = (Person)e;
       // rest of the code
    }But since the argument surname was a String, how to tell a method sort that the field surname was actually chosen?
    If my plan does not makes sense, do tell.
    Thanks.

  • Inheritance Design Question

    I am having a problem of having a problem of how I can go about creating the correct class type. I am reading from a file and the first word in each line is the name of the class I want to create an instance of. And I don't know how I can create an instance of that class by just knowing the class name. I mean I can create the correct class but I don't know how to cast it to the correct type once it is reaturned. Here is my structure of the classes I am talking about.
    public class Segment{]
    public class ISA extends Segment{
      public void setRef01(){ }
      public void setRef02(){ }
      public void setRef03(){ }
      public void setRef04(){ }
    public class IEA extends Segment{
      public void setRef01(){ }
      public void setRef02(){ }
      public void setRef03(){ }
    FileReader reader = new FileReader("myfile.txt");
    String str;
    while((str = reader.readLine()) != null){
      String className = str.substring(0, str.indexOf(" ")).trim();
      Segment seg = getNewSegment(className);
      /*How do I cast it to be of type className either IEA or ISA?
       *I reason is because I need to be able to call setRef04() and
       *I cannot do that b/c it is of the parent type, Segment
    public Segment getNewSegement(String className){
       if(className.equals("ISA"){
         return new ISA();
       }else if( className.equals("IEA"){
         return new IEA();
       }else{
         throw new RuntimeException("Class could not be determined");
    }Any Ideas?
    TIA,
    Doopsterus

    I am confused about class casting. Can you please explain? Also the problem is that since I am going to be calling setRef01 ... setRef02 ... ect depending on the type of object I will have to be constructing the name of the function to call so the sample code would be
                   String segStr = mybuf.substring(0, mybuf.indexOf("|") );
                   String[] tokens = segStr.split("~");
                   Object segment;
                   for(int i = 0; i < tokens.length; i++){
                        if(i == 0){
                             segment = SegmentGetter.getSegmentInstance(tokens);
                             //how do I cast it to the correct type?
                             segment.setSegmentName(tokens[i]);
                        //get the referenceNo
                        String refno;
                        if(i < 10){
                             refno = Segment.getReferenceNo("0"+i);
                        }else{
                             refno = Segment.getReferenceNo(i+"");
                        String functionName = "setRef"+refno;
                        //this does not work... how can I make it work?
                        segment.functionName( tokens[i]);
                   }//end for loop

  • Blatant newbie question: inner classes

    I'm trying to pick up java (finally) and am working my way through the tutorial.
    I am unclear as to how exactly the Class2.java program works, in the Classes and Inheritance lesson (questions page).
    Specifically, when I did the exercise, I 'oopsed' and declared a variable "protected InnerClass2 ic". When I did this, my output showed that "InnerClass1: getAnotherString invoked". When I removed it, it shows "InnerClass2 version of getAnotherString invoked".
    Okay... I understand that I screwed up. I'm just having some problems understanding how the scoping works resulting in my error.
    If somebody could clear this up for me, I'd appreciate it.
    Thanks.
    John.
    (The address of the page is http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-questions.html )

    Sorry, here is the explanation:
    The declaration of the variable ic in the Class2 hides the variable ic in the parent class. When you do not declare this variable in the child class the class of the ic variable in the parent class will be InnerClass2 (because of the line in the Class2 constructor ic= new InnerClass2()), and the type of this variable is InnerClass1.
    Now when you invoke c2.displayStrings() in the main method of the Class2 the parent's displayStrings() method gets invoked (because there is no overriding version of this method in the child class). And in this method two other methods are invoked on the ic variable (which now has the class InnerClass2):
    1 - getString() - which has no overriding version in the InnerClass2 class
    and
    2- getAnotherString() which is overriden in the InnerClass2 class.
    So when you invoke those methods getAnotherString() in the child class will be invoked and you get the result: "InnerClass2 version of getAnother String invoked". If you try to override the other method too (getString()) you will get the result in the overriding version of the method.
    This happens because the class of the variable ic (belonging to Class1) is InnerClass2 and this class has a method which overrides, and therefore hides, the method in the parent class, so the variable ic can only see the overriding version of the original method.

  • Can someone help me clarify a bridge pattern?

    So I have this qualm about bridge patterns. A professor I have is telling me I should never be doing switch statements in my driver if I'm using bridge patterns (except for at object creation), but I think he's wrong and I want to clarify when I think you're going to have to use one of two faux pas.
    Let's take a look at the good old Shape example. So we have a Square and a Circle and we want them to be able to draw themselves. The square uses two points (top left, and bottom right let's say) to draw itself and the Circle uses a center point and a radius to draw itself. It's obvious we need a switch statement at creation to determine which one we're making. My question then comes in, what about when we edit it? Let's say we want to change the points in the rectangle or the point/radius on the circle. We'd either need to do one of two things:
    a) if we put our editShape function in our driver class, we'd have to do a switch to see what type of shape we're editing before we can find out if we need to get input for two points or if we need to get input for a point and a radius length, and then pass that to our edit functions within the objects themselves.
    b) the other option requires we have both objects contain an editShape function (which would probably be an abstract method within Shape that we'd override) and each object would implement them different. Within this function, the object itself is displaying prompts and getting input.
    A is clearly not the right choice, because it results in high coupling and we're having to switch on our objects and we'd have to change the code every time we add new shape classes. B makes sense because we can just call Shape.editShape() from the driver and depending on which type it is it will ask for the proper input from within the object. However, I thought it was bad practice to have input (specifically prompts and scan reads) from within an object.
    Is this where the bridge class comes into play? For example, would I have a ShapeIO class (which could then have an extended ShapeIOConsole class possibly vs a ShapeIOFile class that would read input from a file?) that would contain the prompting from there? And then that class would handle all possible inputs I'd be prompting for?
    E.G. ShapeIOConsole.getPoint() would have the scanner and prompting calls and would return a Point while my Shape.editShape for Square would just call ShapeIO.getPoint() (assuming I have a ShapeIO object within Shape that's been instantiated as a ShapeIOConsole object) to get two points and my Shape.editShape for Circle would call a ShapeIO.getPoint() and a ShapeIO.getRadius? This would mean anytime I have a new Object that has a new type of property to get input for, I'd have to add a function to my ShapeIO, right?
    Anyways, I hope that made some sort of sense. I guess my question is am I correct in most of what I said, if I even said it clear enough for anyone to understand it ^^.

    benirose wrote:
    Thanks for your reply lance! I have a few responses if it's not too much trouble:None at all.
    >
    >
    >>
    That isn't obvious to me at all. Why do you need a switch?
    I would assume you need a switch statement because you need to know what constructor to call, right? For example if you have Shape myShape, wouldn't you need to determine if you're instantiating that as a Square or Circle? I mean you could do it with if statements and not a switch, but you'd need to conditionalize (is that a word?!) the creation, correct?Presumably something has caused the need to instantiate a particular shape. Let's suppose that the action that caused it was that a user pressed a button on a GUI. Now presumably there is a button for a new circle and another button for a new square. Each of these buttons can have their own event handler. The event handler for the 'New Circle' button can instantiate a new circle (or call something else that does it) and the event handler for 'New Square' can instantiate a new square (or call something else that does it). Where does the conditional logic come in?
    It could be that your user interface is a text based list of items to create, and the user has to type a number to choose. In this case, you might need to do some conditional logic, yes.
    Of course there are times when context is not given or insufficient. Often at the fringes of systems, when interacting with other systems, you need to determine what kind of message you've been given before processing it. But even then, there are usually better ways than lots of conditional logic (dispatch tables, for example).
    Having said all of that, I have worked on a system where a GUI had something like 150 different buttons / menu items / other things that could cause actions to occur. The original developer had decided to give each of these things a number so that he could save himself the bother of creating a new ActionListener or whatever for each item, and routed every action through the same switch statement to try to recover the information he'd just thrown away. Bizarre.
    >
    >>
    You could use a visitor rather than doing a switch.
    I don't really know much about the visitor class, but I'll give it a look.
    I assume you mean 'from within a "domain model" class'. I think the bad practice you're referring to is the failure to separate model concerns from view concerns (or, more generally, the failure to separate the concerns of different domains).
    Yeah, I suppose so. I just don't see many classes asking for it's own input, you usually pass it from the driver class. There's no editString() function which asks for input of a new string, you do that in the driver and then set the new string.Try not to think in terms of a 'driver'. This suggests procedural thinking. Think instead of a collaborating eco-system of objects where one object may delegate to another to do some work on it's behalf. The delegator may, when delegating, also give the delegate something that it might find useful to do its work (such as a means of obtaining data or something that it can further delegate some of the work to). If you do it right, the delegate only sees an abstraction appropriate to its place in the eco-system, behind which could exist any number of implementations. If you're just starting out, this may seem a bit heady. Don't worry about it, it'll come...
    >
    >
    >>
    I wouldn't necessarily do any of it this way; I'm only trying to address your question about Bridge. It probably is a good idea to go and talk to your professor again. If you do, come back here and tell us what he said...
    Yeah, I'm not sure I'd do it this way either, but the assignment is a Survey taking program, and the basic implementation was to have an abstract Question class which has a two level inheritence tree of MultipleChoice, Essay, and Matching inheriting from Question, and TF, Short Answer, and Ranking inheriting from MC, Essay, and Matching respectively. So our Survey class would have a Vector of Questions, which is fine, but he said we couldn't do any conditioning to see what type of Question we have, and that we should just be able to make calls to abstract functions in Question that will handle everything.It sounds like he's trying to get you to put behaviour into the Question subclasses, rather than having it in the Survey (i.e. to do what I said above :-). This may feel a bit strange at first, and you might be saying to yourself 'I thought OO was supposed to model the real world, but a question doesn't do anything in the real world'. One of the core concepts in OO is that if you find yourself doing something to an object in the real world, then ask the object to do it for you in your model. That way, system intelligence gets distributed evenly throughout your model.
    You do run into odd issues though. For example, in a library, suppose you have a book and a bookshelf. Supposing the book has just been returned to the library, should the book now goBackToShelf(), or should the shelf receiveBook(). It might even be both under some circumstances. It could also be neither, if you decide that a Librarian is part of your model. But be careful about doing that. You could get all of your behaviour concentrated in the Librarian with everything else in the system being dumb containers of data (some might argue that would be a good thing).
    >
    On a side note, I know if you type a variable with the abstract class (E.G. Question) and then instantiate it as an inherited class (E.G. MC), you can only make calls to the abstract functions (at least Eclipse tells me so). Is it the same way with an interface? What if my Question class wasn't abstract, then I should be fine, right?You can only make calls to the methods declared by Question and it's supertypes (it doesn't matter whether those methods are abstract or not). This is the same for interfaces and it would also be the same if Question was not abstract. The reason is that when you have a declaration like this
    Question question;you are defining a variable called 'question' of type Question. The only things you can ask 'question' to do are those things that its type knows about, which are the methods declared by Question and it's supertypes. The fact that 'question' refers to an object of some subclass of Question doesn't matter. All that matters is the type of the variable, which is Question.
    Regards,
    Lance

Maybe you are looking for

  • I recently purchased U2 Any DVD Ripper on Mac App Store and can not get it to work!  Help!!

    I can not find any documentation on how to use this software.  I can not figure out how to get it to copy a DVD to Mp4 format on my media hard drive, allowing me to watch the video on my apple tv.  Please help or direct me to get a refund for this $1

  • X Y origin point in Illustrator

    I need the x, y origin point to be in the lower left corner. In the past I was able to go into the Adobe Illustrator setting and change some code so when I double clicked in the left corner of the ruler it would switch my origin to lower left. Now th

  • Generic WSDL vs Specific WSDL

    Hi All, Can you list down the differences between Generic WSDL vs Specific WSDL? When do we need to prefer Generic against Specific or vice versa? Also, following are my concerns on Generic WSDL: If my front end application developed is using Generic

  • Text I can't get rid of (InDesign newbie)

    When I insert or add new pages to my document, text appears in the upper left corner which says: "This is a main heading. This is the text. THIS IS A SUB-HEADING This is the text." I can't figure out how to get rid of this text or how to make it not

  • Should i see same camera profiles in LR as i see in ACR?

    I use macintosh and OS 10.6.6 I have found that i can see only the original camera profiles in ACR but can see eric chans's profiles in LR, in addition to the original camera profiles. I have searched ACR, PS, and LR fora, as well as adobe websites a