Results 1 to 8 of 8
  1. #1
    JT4NK3D's Avatar
    JT4NK3D is offline Member
    Join Date
    Nov 2007
    Posts
    50
    Rep Power
    0

    Question Method inheritance

    I have a driver class and two subclasses of it which both implement an interface of 6 methods. One of those methods are implemented exactly the same so i have the exact same block of code in each class. So i thought i would put it in the driver superclass so they could both inherit it. But that causes 2 problems. 1) the subclasses no longer implement it if they inherit in from a superclass(I think, correct me if I'm wrong), and 2) The method calls 2 other methods inside of it. One of which is in the superclass(when the this was in the subclasses, this was no problem as it would just call the method from there since it inherits it), and the other method it calls is in each subclass, but the method is named the same thing for each subclass. So when i put this common method in the superclass so the subclasses inherit it, it can't find the symbol for the method in the subclasses unless i call it with an instance of the subclass. But, that won't work since theres two subclasses i need to use it for. To clear it up:
    Driver SuperClass HWhelper.
    Subclasses DiscountTax & Factor both implement Runnable.
    Interface Runnable implemented by Factor & DiscountTax.
    Runnable methods:
    scanInput(), calcResults(), printResults(), help(), run(), again().
    these are all implemented in Factor & in DiscountTax. But the implementations for again() in each class are identical. I think you can see my problem of putting the method in the superclass now, Because this is the code for again:
    Java Code:
        public void again() {
            System.out.print("Would you like to perform another calculation? (Y/N)");   // ask user
            String choice = input.next();      // store input
            
            while(!(choice.equalsIgnoreCase("Y")) && !(choice.equalsIgnoreCase("N"))    // If the input is invalid
            && !(choice.equalsIgnoreCase("YES")) && !(choice.equalsIgnoreCase("NO"))) {
                System.err.println("\t\t\t*** Error: Invalid Input");                       // print error message and try again
                System.err.println("\t\t\t*** Expecting java.lang.String Y/N/YES/NO");
                System.err.println("\t\t\t*** Discarding input " + choice);
                System.err.println("\n\t Please choose again");
                System.err.print("\t\t\t\t\t");
                choice = input.next();
            }
            
            if((choice.equalsIgnoreCase("Y")) || (choice.equalsIgnoreCase("Yes"))) {    // if they answered yes
                run();
            } else if((choice.equalsIgnoreCase("N")) || (choice.equalsIgnoreCase("No"))) {  // if they answered no
                whereNow();    // where now?
            }
        }
    whereNow() is a method in HWhelper. So when again() is in Factor and DiscountTax, it can run like that since an instance of F/DT(Factor/DiscountTax) is a HWhelper object. run() is a method in DT and a method in F but they are implemented differently, so I cant make a DT object and call run or do the same with F. HELP!:confused: thanks in advance.:):D
    EDIT: I could of course just put the same code in each class but i think there a better way to do it.

    Actually the run methods in each subclass are identical, the only difference is the methods they call - although having the same names (making the run methods identical since they call them in the same order), they call their own methods which are different.
    Last edited by JT4NK3D; 05-30-2008 at 03:13 AM. Reason: add
    You just got T4NK3D!
    Adonrcicg to rcesraeh the haumn mnid is clbapae of rdanieg tihs. -Jvaa Sun Moricyssemts-

  2. #2
    JT4NK3D's Avatar
    JT4NK3D is offline Member
    Join Date
    Nov 2007
    Posts
    50
    Rep Power
    0

    Default

    please someone reply i'm really stuck with this :(
    I really need help i can't move on until i solve this and this thread's been waiting here for a day.
    Last edited by JT4NK3D; 05-30-2008 at 09:57 PM.
    You just got T4NK3D!
    Adonrcicg to rcesraeh the haumn mnid is clbapae of rdanieg tihs. -Jvaa Sun Moricyssemts-

  3. #3
    JT4NK3D's Avatar
    JT4NK3D is offline Member
    Join Date
    Nov 2007
    Posts
    50
    Rep Power
    0

    Default

    please answer someone!
    You just got T4NK3D!
    Adonrcicg to rcesraeh the haumn mnid is clbapae of rdanieg tihs. -Jvaa Sun Moricyssemts-

  4. #4
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Driver SuperClass HWhelper.
    Subclasses DiscountTax & Factor both implement Runnable.
    Interface Runnable implemented by Factor & DiscountTax.
    Runnable methods:
    scanInput(), calcResults(), printResults(), help(), run(), again().

    Some thoughts about your original post:
    Java has a Runnable class. It is generally unwise to name classes the same name as java classes. This is of lesser importance; for later.

    The main thing you must do is to put things together in way that makes sense to you in what you are trying to do. In general, we try to abstract as much as possible up into the abstract/superclass. Sometimes this requires some imagination and experimentation.

    So i thought i would put it in the driver superclass so they could both inherit it. But that causes 2 problems. 1) the subclasses no longer implement it if they inherit in from a superclass(I think, correct me if I'm wrong)
    An easy way to find out what does/n't work is to knock up a simple test app and experiment, something like this:
    Java Code:
    public abstract class InheritanceTest implements processable {
        public static void main(String[] args) {
    
        }
    }
    
    class Test1 extends InheritanceTest {
        public void scanInput() {}
        public void calcResults() {}
        public void printResults() {}
        public void help() {}
        public void run() {}
        public void again() {}
    }
    
    class Test2 extends InheritanceTest {
        public void scanInput() {}
        public void calcResults() {}
        public void printResults() {}
        public void help() {}
        public void run() {}
        public void again() {}
    }
    
    interface processable {
        void scanInput();
        void calcResults();
        void printResults();
        void help();
        void run();
        void again();
    }
    As long as it does what you want and it makes sense to you it is okay. Elegance comes with practice.

    The method calls 2 other methods inside of it. One of which is in the superclass(when the this was in the subclasses, this was no problem as it would just call the method from there since it inherits it),
    A good indication that you're on the right track to refactor some of this into the abstract/superclass.

    and the other method it calls is in each subclass, but the method is named the same thing for each subclass.
    This is where you need to step back and have another look. There may be a better way to put this together. Try looking at this with new eyes and with the idea that there may be a radically different way...
    Last edited by hardwired; 05-31-2008 at 03:17 AM. Reason: format rx

  5. #5
    JT4NK3D's Avatar
    JT4NK3D is offline Member
    Join Date
    Nov 2007
    Posts
    50
    Rep Power
    0

    Default

    Ok i never knew there was already a runnable class, but processable defines what it does better anyways.
    The abstract thing has given me an idea. maybe instead of the interface, Factor and DiscountTax could be subclasses
    of an abstract superclass which could extend the driver class HWhelper. Would this be a good idea?
    You just got T4NK3D!
    Adonrcicg to rcesraeh the haumn mnid is clbapae of rdanieg tihs. -Jvaa Sun Moricyssemts-

  6. #6
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Would this be a good idea?
    It's another possibility. You could try it and see if it suits you.

  7. #7
    JT4NK3D's Avatar
    JT4NK3D is offline Member
    Join Date
    Nov 2007
    Posts
    50
    Rep Power
    0

    Default

    Ok the abstract superclass has been way better till now. Heres the layout:

    PROJECT HomeworkHelper:
    ---------HWhelper---------package homeworkhelper
    ------------|-------------------
    ------------|------------------
    --------<<abstract>>------------
    ---------MathProcess-------package homeworkhelper.math
    ----------|-------|----------------------
    ------.___|-------|___--------------------
    ------|---------------|-------------------
    -DiscountTax--------FactorScanner----- package homeworkhelper.math
    ---------------------------------------

    So i have the same abract methods in MathProcess that i used to have in
    Runnable. Now i' m also putting the again() method in there. heres the code.
    It says where i need help in the comments.. i think there's a way to do it
    , but i dont know how. anyway, :
    Java Code:
    	public void again() {
    		Scanner input = new Scanner(System.in);
    		String choice;
    		System.out.print("Would you like to perform another calculation? (Y/N)");
    		choice = input.next();
    		
    		while(!(choice.equalsIgnoreCase("Y")) && !(choice.equalsIgnoreCase("N")) &&
    			   !(choice.equalsIgnoreCase("YES")) && !(choice.equalsIgnoreCase("NO"))) {
    			System.err.println("\n*** Error - Invalid Input");
    			System.err.println("*** Excpecting java.lang.String Y/N/YES/NO");
    			System.err.println("Discarding input " + choice);
    			System.err.println("Please try again: ");
    			choice = input.next();
    		}
    		
    		input.close();
    		
    		if((choice.equalsIgnoreCase("Y")) || (choice.equalsIgnoreCase("YES"))) {
    			//*************************** NEED HELP HERE********************
    			// maybe and if statement and an if-else something to do with
    			// instanceof FactorScanner/DiscountTax
    		} else if((choice.equalsIgnoreCase("N")) || (choice.equalsIgnoreCase("NO"))) {
    			whereNow();
    		}
    	}
    FactorScanner and DiscountTax both have a run method. Could someone please fill in the code where it says i need help in the comments? I'm thinking there's a way to do it with 'this' or 'instanceof' but i have no clue how. please reply.
    Thanks in advance.
    Last edited by JT4NK3D; 05-31-2008 at 09:34 PM. Reason: typo
    You just got T4NK3D!
    Adonrcicg to rcesraeh the haumn mnid is clbapae of rdanieg tihs. -Jvaa Sun Moricyssemts-

  8. #8
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Just an idea.
    Java Code:
    import java.util.Scanner;
    
    public class InheritanceTest {
        static Scanner input = new Scanner(System.in);
    
        public static void main(String[] args) {
            Test1 test = new Test1();
            System.out.println("test.again = " + test.again());
            new Test2().again();
            input.close();
        }
    
        public void scanInput() {}
        public void calcResults() {}
        public void printResults() {}
        public void help() {}
        public void run() {}
    
        private void whereNow() {
            System.out.println("whereNow");
        }
    
        public boolean again() {
            System.out.print("Would you like to perform another calculation? (Y/N)");
            String choice = input.nextLine();
    
            while(!(choice.equalsIgnoreCase("Y"))   &&
                  !(choice.equalsIgnoreCase("N"))   &&
                  !(choice.equalsIgnoreCase("YES")) &&
                  !(choice.equalsIgnoreCase("NO"))) {
                System.err.println("\n*** Error - Invalid Input");
                System.err.println("*** Excpecting java.lang.String Y/N/YES/NO");
                System.err.println("Discarding input " + choice);
                System.err.println("Please try again: ");
                choice = input.nextLine();
            }
    
            if((choice.equalsIgnoreCase("N")) || (choice.equalsIgnoreCase("NO"))) {
                whereNow();
            }
            return choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("YES");
        }
    }
    
    class Test1 extends InheritanceTest {
        // Override superclass method for local-specific behavior.
        public boolean again() {
            // Get the superclass user-input value.
            boolean choice = super.again();
            System.out.println(getClass().getName() + " again choice = " + choice);
            // Decide local response based on user input.
            if(choice)
                System.out.println("do something in " + getClass().getName());
            // Required for override; may not be useful, can be ignored.
            return choice;
        }
    }
    
    class Test2 extends InheritanceTest {
        public boolean again() {
            boolean choice = super.again();
            System.out.println(getClass().getName() + " again choice = " + choice);
            if(choice)
                System.out.println("do something in " + getClass().getName());
            return choice;
        }
    }

Similar Threads

  1. Inheritance
    By mew in forum New To Java
    Replies: 1
    Last Post: 12-07-2007, 06:08 PM
  2. help with inheritance in hibernate
    By valery in forum JDBC
    Replies: 1
    Last Post: 08-06-2007, 08:44 PM
  3. Inheritance in GUI
    By Marty in forum SWT / JFace
    Replies: 2
    Last Post: 05-11-2007, 12:54 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •