Java Inheritance: Same operations on different data
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: Java Inheritance: Same operations on different data

  1. #1
    Join Date
    Aug 2009
    Posts
    3

    Java Inheritance: Same operations on different data

    Hi,

    Is there a way in Java to implement the following inheritance paradigm: say I have a base class that contains a "data" member of a "base data" type, and a method that does something with that data:

    Code:
    class BaseData {
    ...
    }
    
    class Base {
       BaseData data;
       void doSomethingWithData() {
           ...
       }
    }
    Now, I want several classes that will do the SAME thing with data as the base class, but data of the derived class, NOT the base class.

    Code:
    class DerivedFromBaseData extends BaseData {
       ...
    }
    Code:
    class DerivedFromBase extends Base {
       DerivedFromBaseData data;
       void DoSomethingWithData() {
           ...
        }
    }
    Obviously, I want to avoid repeated code for doSomethingWithData in each derived class--the method should be the same! Only the "data" it operates on should be different in each class. Unfortunatley, the inherited method will operate on the base class "data", not on the "data" specific to the derived class.

    I am sure there is an easy way to do it, I just lack experience in inheritance and ploymorphism to implement it properly. Your help is appreciated. Thanks!

  2. #2
    Join Date
    Aug 2009
    Posts
    3

    Re: Java Inheritance: Same operations on different data

    What I am trying to implement is a "Table" class that will do different operations on a JTable. The "data" member in question is the table model (derived from AbstractTableModel). The "Table" base class will have several derived classes, and each will contain its own table model (since data representation for each table is different). However, I'd like to keep most of the functionality in the base class. For example, there is no reason to repeat methods such as setValueAt() and getValueAt() everywhere. And if I do repeat them in each derived class, I might as well do without inheritance.

    What I was thinking is to leave "model" uninitialized in the base class and in each derived class do something like:

    Code:
    super.model = new Model1();


    where there is a Model1 for DerivedClass1, Model2 for DerivedClass2, ...

    However, besides other problems this will cause, I don't think this solution is "in the spirit" of inheritance, and there should be an easier/more elegant way to do it.

    I don't think the generics example you gave will work here:

    [CODE]
    Base b = new Base();
    b.doSomething(new Type1());
    [\CODE]

    I will be constructing several Table classes, and calling different methods on each one. Methods that will cause changes in the underlying data should modify that table's model. However, the "model" they should change is not the one in the base class, but their own.

    I think there's even a known design pattern for this, I just can't remember it...

  3. #3
    Join Date
    Feb 2008
    Posts
    966

    Re: Java Inheritance: Same operations on different data

    Yeah, that's why I deleted it right away, I was ahead of myself

    So you want something with data types that will follow some kind of pattern like this?
    Code:
    abstract class DataType {
        int n;
        abstract int getN();
        abstract void setN(int n);
    }
    class MyDataType extends DataType {
        public void setN(int n) { this.n = n; }
        public int getN() { return n; }
    }
    
    class YourDataType extends DataType {
        public void setN(int n) { this.n = n; }
        public int getN() { return n; }
    }
    And maybe the base class will work similar to this?
    Code:
    class Base {
        public DataType d;
    
        public void doSomething() {
            System.out.println("Value of n: " + d.getN());
        }
    }
    
    public class DerivedFromBase extends Base {
    
        public static void main(String args[]) {
            DerivedFromBase gc = new DerivedFromBase();
            gc.d = new MyDataType();
            gc.d.setN(1);
            gc.doSomething();
            
            gc.d = new YourDataType();
            gc.d.setN(3);
            gc.doSomething();
        }
    }
    Value of n: 1
    Value of n: 3

  4. #4
    Join Date
    Aug 2009
    Posts
    3

    Re: Java Inheritance: Same operations on different data

    Yes, thank you, I want something like that. Now, the question is, is there a way to eliminate repeating setN() and getN() definitions in all derived classes of DataType (YourDataType, MyDataType)?

    If this helps, what I have with JTable's is roughly like this:

    Code:
    class TableModel extends AbstractTableModel {
    	//...
    }
    
    class Table {
    	JTable table;
    	TableModel model;
    	
    	public Object getValueAt(int row, int col) {
    		return model.getValueAt(row, col);
    	}
    	
    	public void setValueAt(Object value, int row, int col) {
    		model.setValueAt(value, row, col);
    	}
    }
    
    //Now, I have a set of specialized Table's, each with a specialized TableModel, e.g.
    
    class CarTableModel extends TableModel {
    	//...
    }
    
    class CarTable extends Car {
    	JTable table;
    	CarTableModel model
    
    	public void addCarType() {
    		//..
    	}
    }
    All I want is to avoid duplicating a bunch of methods such as getValueAt and setValueAt, which should be handled by the base class. The only methods I want in the derived classes are the ones specific to CarTable. So, what I want is getValueAt and setValueAt to operate on CarTable.model, rather than Table.model, when I write:

    CarModel carModel = new CarModel();
    carModel.setValueAt("Nissan", 3, 2);

  5. #5
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Java Inheritance: Same operations on different data

    I don't see the problem with each subclass assigning its own data model to the data model reference in the abstract superclass. For some reason, you didn't think it was 'in the spirit of inheritance' (can you explain why?), and would cause 'other problems' (what other problems?). It solves the problem you specified with a single line of constructor code by giving each subclass its own data model and leaving all the data manipulation to the abstract superclass.

    What am I missing? If there are other considerations you haven't mentioned, perhaps now would be a good time...

    You could consider instantiating an empty data model in the superclass and filling it in the subclass constructor, but I don't see any particular advantage to doing that.

    If you don't think carefully, you might believe that programming is just typing statements in a programming language...
    W. Cunningham
    Last edited by dlorde; August 4th, 2009 at 06:50 PM.
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  6. #6
    Join Date
    Feb 2008
    Posts
    966

    Re: Java Inheritance: Same operations on different data

    Quote Originally Posted by java_learner View Post
    Yes, thank you, I want something like that. Now, the question is, is there a way to eliminate repeating setN() and getN() definitions in all derived classes of DataType (YourDataType, MyDataType)?
    Of course you can, an abstract class can have concrete methods:
    Code:
    abstract class DataType {
        int n;
        public void setN(int n) { this.n = n; }
        public int getN() { return n; }
    }
    class MyDataType extends DataType {
    
    }
    
    class YourDataType extends DataType {
    
    }
    But like dlorde is getting at is: what now is the difference between the sub classes? Are they just empty shells with a name? What is the point of that?

  7. #7
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Java Inheritance: Same operations on different data

    Quote Originally Posted by ProgramThis View Post
    .. what now is the difference between the sub classes? Are they just empty shells with a name? What is the point of that?
    Of course, you're right - it was late when I posted, and I missed the logical conclusion - that the polymorphism is only in the data model (which implies just the data), so it isn't really polymorphism at all - it's just different data for different uses.

    In theory, there is no difference between theory and practice, but not in practice...
    Anon.
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  8. #8
    Join Date
    May 2009
    Posts
    2,413

    Re: Java Inheritance: Same operations on different data

    Quote Originally Posted by java_learner View Post
    I am sure there is an easy way to do it
    The easy way is to use dynamic inheritance rather than static.

    There's a trick involved. You split the base class into an interface and an implementation class. It goes like this,

    Code:
    class Base {
       public void methodA() {
       }
    }
    The above base class is split into
    Code:
    interface Base_Interf {
       void methodA();
    }
    class Base_Impl implements Base_Interf {
       public void methodA() {
       }
    }
    Now instead of using static inheritance in a derived class like

    Code:
    class Derivered extends Base {
    }
    you do,

    Code:
    class Derivered implements Base_Interf {
       private Base_Impl bi = new Base_Impl();
       public void methodA() { // implements interface
          bi.methodA(); // calls implementation by delegation
       }
    }
    As you can see the derived class now will behave exactly like before from the outside. It's just that it's free to switch implementations inside (which actual implementation is used will be determined by which implementation object the bi variable holds).

    You could have a number of Base_Impl classes like Base_Impl_1, Base_Impl_2 etcetera and even switch between them at runtime if you wish.

    Or you could have different derived class like Derived_1, Derived_2 etcetera, each using Base_Impl_1 and Base_Impl_2 respectively.

    So dynamic inheritance means the derived classes aren't restricted to use the one implementation inherited from the base class only. Instead they're free to use whichever implementation suits their liking. And they can even switch at runtime, thus "dynamic".
    Last edited by nuzzle; August 11th, 2009 at 03:54 AM.

  9. #9
    Join Date
    May 2009
    Posts
    2,413

    Re: Java Inheritance: Same operations on different data

    Further to my post above I can say that dynamic inheritance is used in two major situations.

    1. In the so called State design pattern.

    Here the "gut" of an object is changed at runtime.

    2. To simulate multiple inheritance of implementation.

    Java supports single inheritance of implementation only (you can extend at the most one class) and multiple inheritance of type (you can implement as many interfaces as you wish).

    Dynamic inheritance splits a class (with implementation) into an interface and an implementation class. This means the classes you couldn't extend now suddenly are interfaces which you can implement, so in this way you can esaily simulated multiple inheritance in Java (and doesn't need to switch to C++ to get that )
    Last edited by nuzzle; August 16th, 2009 at 05:53 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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center