Another about inheritance

Well, in my monopoly game there is something I don't in the right way I guess.
What I want to do
I'd like, when the player lands on on a square, to display a panel in the center of the board with the square fields - say price, rent, owner for a street, tax for community chest and so on.
[What I have[/b]
I have a square abstract class wih subclasses, street, station, etc.
In my Swing GUI, I have a SquareView, implementing a View interface with this single method :
updateView();
[b]The problem
When my player lands on he square, it fires a custom eventn firePlayerLanded(). Now, in my SquereView class, I have a reference to a Square object (the base class, since I cannot konw before the board is built which type of sqquare it will be).
So, When I try and get info from the Square member of my SquareView, I have only BASIC finctions of the Square : it's title, id, etc. NOT the functions related to the subclasses, like 'owner', for a street or a station, nor "rent' for a street only.
So, here's my question : how can I create a dynamic object from this context, not knowing before compile time which type of square I'll have to deal with (furthermore, my board is built from an XML file, and it would be nice if the user could change the board layout, creating a new one and not breaking the game).
I thought of the Factory pattern, but examples I read always have to call a construtor with the correct type at any moment.
Could you help me with this one, even if it involves refactoring the data structure ?
Thanks in advance !
PS : hope it is clear enough. Tell me if it isn't :)

Well, the articles are rather disturbing, after all
these reading (in Java but also C++ before) about
model not knowing anything of its view()s :)In his articles, the model itself doesn't refer to the view, but the view is often an inner class of the model.
Ask your self: is your model going to have many different views, if not, his approach works well.

Similar Messages

  • A little question about inheritance

    Can someone explain this to me?
    I have been reading about inheritance in Java. As I understand it when you extend a class, every method gets "copied" to the subclass. If this is so, how come this doesn't work?
    class inherit {
        int number;
        public inherit(){
            number = 0;
        public inherit(int n){
            number = n;
    class inherit2 extends inherit{
        public inherit2(int n, int p){
            number = n*p;
    class example{
        public static void main(String args[]){
            inherit2 obj = new inherit2();
    }What I try to do here is to extend the class inherit with inherit2. Now the obj Object is of inherit2 class and as such, it should inherit the constructor without parameters in the inherit class or shouldn't it ??? If not, then should I rewrite all the constructors which are the same and then add the new ones??

    I believe you were asking why SubClass doesn't have the "default" constructor... after all, shouldn't SubClass just have all the contents of SuperClass copy-pasted into it? Not exacly. ;)
    (code below... if you'd like, you can skip the first bit, start at the code, and work your way down... depending on if you just started, the next bit may confuse rather than help)
    Constructors are special... interfaces don't specify them, and subclasses don't inherit them. There are many cases where you may not want your subclass to display a constructor from it's superclass. I know this sounds like I'm saying "there are many cases where you won't want a subclass to act exactly like a superclass, and then some (extend their functionality)", but its not, because constructors aren't how an object acts, they're how an object gets created.
    As mlk said, the compiler will automatically create a default constructor, but not if there is already a constructor defined. So, unfortunatley for you, there wont be a default constructor made for SubClass that you could use to create it.
    class SuperClass { //formerly inherit
    int number;
    public SuperClass () { //default constructor
    number = 0;
    public SuperClass (int n) {
    number = n;
    class SubClass extends SuperClass { //formerly inherit2
    //DEFAULT CONSTRUCTOR, public SubClass() WILL NOT BE ADDED BY COMPILER
    public SubClass (int n, int p) {
    number = n*p;
    class Example {
    public static void main(String [] args) {
    //attempted use of default constructor
    //on a default constructorless subclass!
    SubClass testSubClass = new SubClass();
    If you're still at a loss, just remember: "Constructors aren't copy-pasted down from the superclass into the subclass!" and "Default constructors aren't added in if you add your own constructor in" :)
    To get it to work, you'd have to add the constructor you used in main to SubClass (like doopsterus did with inheritedClass), or use the constructor you defined in SubClass for when you make a new one in main:
    inherit2 obj = new inherit2(3,4);
    Hope that cleared things up further, if needed. By the way, you should consider naming your classes as a NounStartingWithACapital, and only methods as a verbStartingWithALowercase

  • One very basic question about inheritance

    One very basic question about inheritance.
    Why we need inheritance?
    the benefit of inheritance also achieve by creating instance of base class using it in other class instead of extending the base class.
    Can any one please explain why we are using inheritance instead of creating object of base class????

    SumitThokal wrote:
    One very basic question about inheritance.
    Why we need inheritance?
    the benefit of inheritance also achieve by creating instance of base class using it in other class instead of extending the base class.
    Can any one please explain why we are using inheritance instead of creating object of base class????What did you find out when you looked on Google?
    One example of inheritance comes in the form of a vehicle. Each vehicle has similarities however they differ in their own retrospect. A car is not a bus, a bus is not a truck, and a truck is not a motorbike. If you can define the similarities between these vehicles then you have a class in which you can extend into either of the previous mentioned vehicles. Resulting in a reusable class, dramatically reduces the size of code, creates a single point of definition, increases maintainability, you name it.
    In short there are thousands of benefits from using inheritance, listing the benefits could take a while. A quick Google search should give you a few hundred k if not million links to read.
    Mel

  • A question about inheritance and overwriting

    Hello,
    My question is a bit complicated, so let's first explain the situation with a little pseudo code:
    class A {...}
    class B extends A{...}
    class C extends B {...}
    class D extends C {...}
    class E extends B {...}
    class F {
      ArrayList objects; // contains only objects of classes A to E
      void updateObjects() {
        for(int i = 0; i < objects.size(); i++)
          A object = (A) objects.get(i); // A as superclass
         update(A);
      void update(A object) { ... }
      void update(B object) { ... }
      void update(D object) { ... }
    }My question now:
    For all objects in the objects list the update(? object) method is called. Is it now called with parameter class A each time because the object was casted to A before, or is Java looking for the best fitting routine depending on the objects real class?
    Regards,
    Kai

    Why extends is evil
    Improve your code by replacing concrete base classes with interfaces
    Summary
    Most good designers avoid implementation inheritance (the extends relationship) like the plague. As much as 80 percent of your code should be written entirely in terms of interfaces, not concrete base classes. The Gang of Four Design Patterns book, in fact, is largely about how to replace implementation inheritance with interface inheritance. This article describes why designers have such odd beliefs. (2,300 words; August 1, 2003)
    By Allen Holub
    http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html
    Reveal the magic behind subtype polymorphism
    Behold polymorphism from a type-oriented point of view
    http://www.javaworld.com/javaworld/jw-04-2001/jw-0413-polymorph_p.html
    Summary
    Java developers all too often associate the term polymorphism with an object's ability to magically execute correct method behavior at appropriate points in a program. That behavior is usually associated with overriding inherited class method implementations. However, a careful examination of polymorphism demystifies the magic and reveals that polymorphic behavior is best understood in terms of type, rather than as dependent on overriding implementation inheritance. That understanding allows developers to fully take advantage of polymorphism. (3,600 words) By Wm. Paul Rogers
    multiple inheritance and interfaces
    http://www.javaworld.com/javaqa/2002-07/02-qa-0719-multinheritance.html
    http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html
    http://www.artima.com/intv/abcs.html
    http://www.artima.com/designtechniques/interfaces.html
    http://www.javaworld.com/javaqa/2001-03/02-qa-0323-diamond_p.html
    http://csis.pace.edu/~bergin/patterns/multipleinheritance.html
    http://www.cs.rice.edu/~cork/teachjava/2002/notes/current/node48.html
    http://www.cyberdyne-object-sys.com/oofaq2/DynInh.htm
    http://www.gotw.ca/gotw/037.htm
    http://www.javajunkies.org/index.pl?lastnode_id=2826&node_id=2842
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=001588
    http://pbl.cc.gatech.edu/cs170/75
    Downcasting and run-time
    http://www.codeguru.com/java/tij/tij0083.shtml
    type identification
    Since you lose the specific type information via an upcast (moving up the inheritance hierarchy), it makes sense that to retrieve the type information ? that is, to move back down the inheritance hierarchy ? you use a downcast. However, you know an upcast is always safe; the base class cannot have a bigger interface than the derived class, therefore every message you send through the base class interface is guaranteed to be accepted. But with a downcast, you don?t really know that a shape (for example) is actually a circle. It could instead be a triangle or square or some other type.
    To solve this problem there must be some way to guarantee that a downcast is correct, so you won?t accidentally cast to the wrong type and then send a message that the object can?t accept. This would be quite unsafe.
    In some languages (like C++) you must perform a special operation in order to get a type-safe downcast, but in Java every cast is checked! So even though it looks like you?re just performing an ordinary parenthesized cast, at run time this cast is checked to ensure that it is in fact the type you think it is. If it isn?t, you get a ClassCastException. This act of checking types at run time is called run-time type identification (RTTI). The following example demonstrates the behavior of RTTI:
    //: RTTI.java
    // Downcasting & Run-Time Type
    // Identification (RTTI)
    import java.util.*;
    class Useful {
    public void f() {}
    public void g() {}
    class MoreUseful extends Useful {
    public void f() {}
    public void g() {}
    public void u() {}
    public void v() {}
    public void w() {}
    public class RTTI {
    public static void main(String[] args) {
    Useful[] x = {
    new Useful(),
    new MoreUseful()
    x[0].f();
    x[1].g();
    // Compile-time: method not found in Useful:
    //! x[1].u();
    ((MoreUseful)x[1]).u(); // Downcast/RTTI
    ((MoreUseful)x[0]).u(); // Exception thrown
    } ///:~
    As in the diagram, MoreUseful extends the interface of Useful. But since it?s inherited, it can also be upcast to a Useful. You can see this happening in the initialization of the array x in main( ). Since both objects in the array are of class Useful, you can send the f( ) and g( ) methods to both, and if you try to call u( ) (which exists only in MoreUseful) you?ll get a compile-time error message.
    If you want to access the extended interface of a MoreUseful object, you can try to downcast. If it?s the correct type, it will be successful. Otherwise, you?ll get a ClassCastException. You don?t need to write any special code for this exception, since it indicates a programmer error that could happen anywhere in a program.
    There?s more to RTTI than a simple cast. For example, there?s a way to see what type you?re dealing with before you try to downcast it. All of Chapter 11 is devoted to the study of different aspects of Java run-time type identification.
    One common principle used to determine when inheritence is being applied correctly is the Liskov Substitution Principle (LSP). This states that an instance of a subclass should be substitutible for an instance of the base class in all circumstances. If not, then it is generally inappropriate to use inheritence - or at least not without properly re-distributing responsibilities across your classes.
    Another common mistake with inheritence are definitions like Employee and Customer as subclasses of People (or whatever). In these cases, it is generally better to employ the Party-Roll pattern where a Person and an Organization or types of Party and a party can be associated with other entities via separate Role classes of which Employee and Customer are two examples.

  • Question about inheritance

    I'm attempting to write Monopoly and I'm having some inheritance problems. Every space on the board is first and foremost of type BoardSpace however some of them are of type Property which extends BoardSpace and some are of type Chance/Community which also extend BoardSpace etc. Depending on what type of space it is something different happens. Right now heres how a couple of classes look. I'm having a problem where if I land on a space that doesn't define its own action method, it defaults to the BoardSpace action method as it should yet it goes into that if statement even when it clearly shouldn't be. Like if I land in jail, it will still go into that if statement, and it will print Jail (3 times). Is this something funky with inheritance?
    BoardSpace:
    public class BoardSpace extends JPanel
         Location loc;
         String name;
         public BoardSpace(String s, Location l)
              loc = l;
              name = s;
         public void action(Player p)
              if(name.equals("Go"));//If name is "go" how can it also be "jail" ?
                   System.out.println(name);
                   System.out.println(this.name);
                   System.out.println(p.spot.name);
                   p.money+=200;
    }Property:
    import javax.swing.*;
    public class Property extends BoardSpace
         Player owner = null;
         public Property(String s, Location l)
              super(s,l);
         public void action(Player p)
              if(owner!=null && owner!=p)
                   JOptionPane.showMessageDialog(this,"You landed on "+this.name+".\n This property is owned by Player" +owner.number+".\n You owe $5");
              else
                   JOptionPane.showInputDialog("Buy?");
    }

    duckbill wrote:
    Hint: you can launch JOptionPane dialogs without a single panel, frame etc...
    #You can also launch dialogs with panels, frames, etc... but without subclassing Property from JPanel
    Edited by: DrLaszloJamf on Oct 3, 2007 12:42 PM

  • Trouble about inherited property icon

    Hi,
    I think the answer to this question is wrong: http://www.shiaupload.ir/images/05580302874684517163.jpg (here is the image sample)
    But the answer shouldn't have been C? Because an inherited property that has been changed is displayed with a red cross icon.
    Thanks.

    Hello Roger,
    Yes, you are right.
    The correct answer is C.
    The question refers to Variant Property, which is displayed with a red cross over an arrow.
    Regards,
    Alex
    If someone's answer is helpful or correct please mark it accordingly.

  • Question about inheritance and  casting

    according to the java api it said Calendar() is a super-class of GregorianCalendar(). with that said it means GC inherits all members of C(). i hope everyone agrees with me here.
    why is it necessary to do this:
    Calendar c = new GregorianCalendar();//by the way this is called implicit casting per the java tutorial.if GC inherits everything from C, and if you need members from both classes, then wouldn't it be enough to just do
    GregorianCalendar gc = new GregorianCalendar();why is it necessary to declare a variable of the parent class and assign a subclass reference to that variable?

    then why does the tutorial show this?Why not? It's legal Java. It's what I would probably write, unless I knew I was going to use some methods that were in GregorianCalendar and not in Calendar.

  • Another about Push on Germany

    Hello guys!
    So, I´m going to Germany for some days, and I´m plannyng to buy an iPad there (you see, it is really cheaper than here in Brazil).
      The question is:
    Will Push Notifications work when I'll be back to Brazil?
    I imagine that YES, It´ll work, because this is an "issue" just within the Germany´s borders. But I´d like to hear from you.

    Andy,
    i'm not that much of a memory expert either but:-
    1) You might find more choice PC Memory Upgrade UK i've used them & their ok. Their about the only UK supplier that carries a lot of the makes u see around.
    2) See Sticky - RAM that works well with MSI K8N motherboards
    3) If i'm looking like u i try to do a web search & pick up some reviews that either use the same CPU & chipset, if not the mobo.
    You might find this a good starting point Rebels Haven - High Performance Memory And The MSI Neo2 Platinum
    4) Keep same thread    & you'll  most likely get some advise from more knowledgable people.
    luck

  • ? about inheritance i guess

    im not sure if this is considered inheritance
    and i have a question
    say i want to have 3 classes
    class point
    class polygon
    class shapes
    then say i want to have a class that does all the real work
    class animate
    now this is fine if i want to simply extend my classes right
    but what if i have a class called ai or so that has nothing to do with any of those and i want to add it to the animate class is that considered multiple inheritance?

    Multiple inheritance was a issue that was sidestepped by the originators of Java. It causes some problems which are too deep to get into here. Take a look at the Java 2D API to get an idea of how the experts handled it.
    http://java.sun.com/j2se/1.3.0/docs/guide/2d/spec/j2d-bookTOC.doc.html

  • Quick question about inheritance and exceptions

    If I have two classes like this:
    public class ClassA {
        public void myMethod() throws NumberFormatException {
          throw new NumberFormatException();
    public class ClassB extends ClassA {
        public void myMethod() {
    }Does myMethod() in classA override myMethod in classB?
    And why?
    Thank you,
    V

    I just want to add that since NumberFormatException is
    a descendant of RuntimeException, you are not required
    to declare that the method throws this exception. Some
    people think it is a good idea to declare it anyway
    for clarity. Personally, I don't think so.I agree.
    I think Sun recommends that you don't declare unchecked exceptions in the method declaration, but do document them in the javadoc comments.

  • Promblem about inheritance and saving data

    I have Product class (super class) and Kitchen class (sub class). When I want to create a Kitchen object and write it to a *.txt file. However the error occurs: "java.lang.NullPointerException". What is going wrong? Please help. Thanks
    Product class
    public Product(int aProductID, String aProductName, String aOriginalCountry,
                        double aWeight, double aPrice, String aProductCategory,
                        String aInputDate, String aExpiryDate, double aVatPrice,
                        String aManufacturerName, String aManufacturerAddress,
                        String aWarranty)
        productID = aProductID;
        productName = aProductName;
        originalCountry = aOriginalCountry;
        weight = aWeight;
        price = aPrice;
        productCategory = aProductCategory;
        inputDate = aInputDate;
        expiryDate = aExpiryDate;
        vatPrice = aVatPrice;
        manufacturerName = aManufacturerName;
        manufacturerAddress = aManufacturerAddress;
        warranty = aWarranty;
      }Kitchen class
    public Kitchen(int aProductID, String aProductName, String aOriginalCountry,
                         double aWeight,
                         double aPrice, String aProductCategory,
                         String aInputDate, String aExpiryDate, double aVatPrice,
                         String aManufacturerName, String aManufacturerAddress,
                         String aWarranty)
       super(aProductID, aProductName, aOriginalCountry, aWeight, aPrice,
               aProductCategory, aInputDate, aExpiryDate, aVatPrice,
             aManufacturerName, aManufacturerAddress, aWarranty);
    }The method that write the method to text file
    public void writeInfo()
        try{
          PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter
          ("C:\\Documents and Settings\\Charles\\My Documents\\Kitchen.txt", true)));
          out.println();
          out.write(Integer.toString(productID));
          out.write("  ");
          out.write(productName);
          // More data to write...
          out.flush();
          out.close();
         catch(IOException ex)
            ex.printStackTrace();
    }

    This is the Product Class
    package supermarket;
    import java.io.*;
    import javax.swing.*;
    public class Product {
      // Declare variables
      protected int productID;
      protected String productName;
      protected String originalCountry;
      protected double weight;
      protected double price;
      protected String productCategory;
      protected String inputDate;
      protected String expiryDate;
      protected double vatPrice;
      protected String manufacturerName;
      protected String manufacturerAddress;
      protected String warranty;
      protected double originalPrice;
      protected double calculatedVATPrice;
      public Product() {
        productID = 0;
        productName = "";
        originalCountry = "";
        weight = 0.0;
        price = 0.0;
        vatPrice = 0.0;
        manufacturerName = "";
        manufacturerAddress = "";
        warranty = "YES";
      public Product(int aProductID, String aProductName, String aOriginalCountry,
                           double aWeight, double aPrice, String aProductCategory,
                           String aInputDate, String aExpiryDate, double aVatPrice,
                           String aManufacturerName, String aManufacturerAddress,
                           String aWarranty)
        productID = aProductID;
        productName = aProductName;
        originalCountry = aOriginalCountry;
        weight = aWeight;
        price = aPrice;
        productCategory = aProductCategory;
        inputDate = aInputDate;
        expiryDate = aExpiryDate;
        vatPrice = aVatPrice;
        manufacturerName = aManufacturerName;
        manufacturerAddress = aManufacturerAddress;
        warranty = aWarranty;
      public void writeInfo()
        try{
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter
        ("C:\\Documents and Settings\\Charles\\My Documents\\testing.txt", true)));
        out.println();
        out.write(Integer.toString(productID));
        out.write("  ");
        out.write(productName);
        out.write("  ");
        out.write(originalCountry);
        out.write("  ");
       // and more data to save...
        out.flush();
        out.close();
        catch(IOException ex)
         ex.printStackTrace();
    public void displayInfo(JLabel D1)
        try
          BufferedReader in = new BufferedReader(new FileReader
          ("C:\\Documents and Settings\\Charles\\My Documents\\testing.txt"));
          String fromAll = in.readLine();
          D1.setText(fromAll);
        catch(IOException ex)
        ex.printStackTrace();
    }This is the Kitchen class
    package supermarket;
    import supermarket.Product;
    import java.io.*;
    import javax.swing.*;
    public class Kitchen extends Product{
          private int productID;
          private String productName;
          private String originalCountry;
          private double weight;
          private double price;
          private String productCategory;
          private String inputDate;
          private String expiryDate;
          private double vatPrice;
          private String manufacturerName;
          private String manufacturerAddress;
          private String warranty;
          private double originalPrice;
          private double calculatedVATPrice;
         public Kitchen() {
         super();
      // The constructor is not working......
      public Kitchen(int aProductID, String aProductName, String aOriginalCountry,
                          double aWeight, double aPrice, String aProductCategory,
                         String aInputDate, String aExpiryDate, double aVatPrice,
                         String aManufacturerName, String aManufacturerAddress, String aWarranty)
       super(aProductID, aProductName, aOriginalCountry, aWeight, aPrice,
                aProductCategory, aInputDate, aExpiryDate, aVatPrice,
                aManufacturerName, aManufacturerAddress, aWarranty);
    public void writeInfo()
        try{
          PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter
         ("C:\\Documents and Settings\\Charles\\My Documents\\Kitchen.txt", true)));
          out.println();
          out.write(Integer.toString(productID));
          out.write("  ");
          out.write(productName);
          out.write("  ");
          out.write(originalCountry);
          // and more data to save...
          out.flush();
          out.close();
    catch(IOException ex)
      ex.printStackTrace();
    public void displayInfo(JLabel E1)
       try
         BufferedReader in = new BufferedReader(new FileReader
        ("C:\\Documents and Settings\\Charles\\My Documents\\Kitchen.txt"));
         String fromAll = in.readLine();
         E1.setText(fromAll);
       catch(IOException ex)
         ex.printStackTrace();
    }Is this look better? Please help. Thanks

  • A question about Inheritance

    Hi,
    I have created a class which implements java.sql.Connection.
    class newConnnection implements Connection{
        close(){
            freeConnection();
    }In my main class I am assigning newConnection object to a Connection object because I want to use the Connection's close method to actually close the connection.
    main{
        newConnection newConn = newConnection();
        Connection conn = (Connection)newConn
        conn.close();
    }But it doesn't use the Connection class method. It uses the newConnection class method. Is there any way I can make use of the Connection method close?
    Thanks.

    But here's what I'm actually doing:
    I think that there is still a way I can use the Connection object.
    // Close all connections in the connection list
         public void closeConnections(Vector connList) throws SQLException{
              Enumeration connections = connList.elements();
              while(connections != null && connections.hasMoreElements()){
                   Connection connection = (Connection)connections.nextElement();
                   if(!connection.isClosed())
                        connection.close();
    connections contains objects but they are the newConnection objects. So when they get assigned to connection, connection actually turns into newConnection and ends up calling the newConnection.close() method

  • About Inheritance and interface!

    I have to write a PQueue2 class which implements PriorityQueue interface, also PQueue2 has to extend BinaryHeap,
    so at the top of the PQueue2 I should have this right?
    public class PQueue2 extend BinaryHeap implements PriorityQueue {

    I meant that if PQueue2 extends BinaryHeap
    then it can call directly all the functions in the
    e BinaryHeap right? but it can also add new methods?It's more like the public and protected methods in BinaryHeap are also the methods of PQueue2. If I create a PQueue2 outside of either class, I can call any public method defined in BinaryHeap on PQueue2.
    the extends keyword creates an "is a" relationship between a class and the class it extends. Every PQueue2 instance is an instance of BinaryHeap (but not the other way around.)

  • Private - encapsulation or inheritance (but not both)

    Suppose that your class has some internal computation or logic that it performs, and that you wish to encapsulate this in a method that can not be called by other classes.
    You provide public methods that filter, format, or somehow modify the input and/or output of this encapsulated method.
    class pseudoCodeClass {
    private coreLogic(Objects inputs) {
    Maybe some complicated math stuff;
    Or password stuff;
    Or pay out functionality for a slot machine;
    return(stuff);
    public getUserData(inputs) {
    format/check the inputs;
    coreLogic(inputs);
    format the output;
    Now, how do you leveradge the power of OO inheritance to extend the internal logic that you encapsulated? If you make the interal logic private, then it's encapsulated, but you lose the power of OO inheritance, or you can make it protected and lose the encapsulation. I thought an OO language was supposed to have encapsulation and inheritance, not encapsulation or inheritance. (And, yes I realize that there is some techincal sense in which private methods are still inherited, but I'm talking about the general OO concept of inheritence where it includes overriding or extending.)
    Suppose you want to:
    class pseudoCodeSubclass extends pseudoCodeClass {
    private coreLogic(inputs) {
    super.coreLogic(inputs);
    additional more specific code; // The whole point of OO inheritence
    You can't extend super.coreLogic through your access to super.getUserData because it does all sorts of filtering and formating that is not a part of the internal logic that you wish to extend/override. And, providing other more public accessor methods to the core logic just defeats the encapsulation.
    I have seen many discussions of this, but none with any answers to my satisfaction. One line of answers is that you don't want encapsulated stuff to be part of your object's contract. Some times people with this sort of answer even suggest coppying the code from the super class into the subclass. People with this sort of answer don't seem to even want the option to use inheritence because of the obligation that might go with it. But without the option of inheriting encapsulated logic, they are forced to either use cut and paste (in an OO language that seems wrong to me) or to abandon encapsulation all together. Being forced into those 2 extreems doesn't seem to me like it would simplify future support of your class, and future support seems to be the primary point of the contract line of response.
    The way some people argue about this, I amost want to say - Look! In C you can encapsulate everything you want, and never have to worry about inheritance. (But you still shouldn't have to cut and paste.)
    Another line of response that I have seen is that private methods should only be used in breaking up code that would have gone into a single method. In other words, the private methods aren't really 'units of program logic' they are just a mater of organizational convenience. So if you had:
    public oneBigMessyMethod() {
    100 lines of A;
    100 lines of B;
    100 lines of C;
    you could maintain it as:
    public oneBigMessyMethod() {
    a();
    b();
    c();
    private a() {
    100 lines of A;
    private b() {
    100 lines of B;
    private c() {
    100 lines of C;
    I agree private works well in this situation. Presumably since a(), b() and c() are divided up for convenience rather than because of distinct logical function, you wouldn't want to extend just a() with inheritance. But this also seems to dodge the question. Just because sometimes you might not want encapsulated functionality to be available for extention, does not mean that you would never want it. I think that I'd also have to disagree with the permise that encapsulation is only for hiding stuff that is just a convention of convenience. The main point of encapsulation is to hide information or functionality. If encapsulation is only used for the convenient breakdown of your primary functionality, then all of your primary functionality is public, package or protected. That does make it inheritable. But, now all of the primary functionality is a part of the contract for that class.
    Is there an answer to this issue that does not ignore the value of either encapsulation or inheritance?
    There is one way that I can see to do exactly what I think should be possible. That is to put only classes from the same hierarchy in a package. Then both package and protected effectively provide encapsulation with the ability to inherit (and you do still have the option to use private or final if there is a case where you want to disable inheritence).
    What I'd like to know is - What do people actually do? In the real world, do people:
    1) use private + cut and paste
    2) use package/protected + self discipline
    Where 2 is that you drop encapsulation within your package but then excercise self dicipline and just don't call/access stuff that you intend to be for that class only...
    Or is there some 3rd thing that I'm missing? I've tried to think how maybe you could design your objects in such a way that you'd never need to inherit/extend something that you would also want to encapsulate. But I just don't see how that's possbile.
    So, what do people do?
    Chris

    First of all, you have got to understand that I am not
    suggesting that Private and Final should be changed or
    removed from java. It looks to me like there should
    be an additional access option (and there was
    originaly).
    I understand that if a class inherits something, it
    could expand the access or put public accessor methods
    around it. Obviously with ultra sensitive code this
    would be a nightmare. So private and final are very
    important. But if the very possibility of another
    class expanding a given level of access is a reason
    for not even having that level of access, then why do
    we have package and protected?
    There are a great number of places in common coding where that access does restrict usage in a usable way.
    >
    If the only re-use of your code that you allow is
    through the public interface, what do you even need an
    OO language for? Just for the polymorphism and a
    different way to organize your code?
    Not sure what you mean by that but see below.
    But as I've said. I've seen this whole thing argued a
    number of times. But what I haven't seen is any
    explanation of what people who take the poslition that
    I'm taking actually do when they write code. Because
    I can sit here with a bunch of other people and say 'I
    wish Java had this or that'. And then of couse a
    bunch of people will resopond and say 'no that's dumb'
    or 'I don't see the point'. But at the end of the
    day, Java still is what it is. So, arguing about what
    it 'should be' is not going to effect how anyone
    codes.
    Sure it can. That is why java now has assert().
    So, what I started out wanting to know is how people
    actually code. Particularly people who wish that Java
    had a subclass only access modifier.
    I don't wish that.
    Perhapse I should also be asking about how things are
    done by people who see this level of access as
    unnececary. How they code is easy enough to
    understand. Making everything that is not intended to
    be accessed by any other class private is easy enough
    to do. But what would be interesting to know is how
    do you design your classes to leveradge inheritance if
    you do this. Maybe there is some way of desinging
    around ever having 'internal functionality' that you
    would want to extend and I'm just not getting it.
    There are three broad classifications of objects.
    1. Those that only use encapsulation
    2. Correct inheritence hierarchies
    3. Incorrect inheritence hierarchies
    The first of those, which I consider most classes to fall into, do not need this.
    The third area occurs when programmers use inheritence as a convenience mechanism to propogate behavior amoung different classes rather than using encapsulation as should be done. They don't understand the difference between "is-a" relationships (design) and coding convienence. I would estimate that at least 50% of existing object hierarchies fall into this area. Since in this case the entire design is wrong an extension is not needed.
    The second area is the only correct area where this might be needed. Since I personally believe that very few classes belong in hierarchies and this proposed extension would only be useful in a sub fraction of those. Since the correct usage is so small I don't think it would be useful addition to the language.

  • Parameterized inheritance and implementation

    I'm learning generics, and I'm having a problem getting the following to work
    I have a base class with some data/behavior
    public abstract Base<E> {
    //...Then there is a concrete class that extends Base and implements Map
    public Concrete<E extends Object & Map<K,V>> extends Base<E extends Object & Map<K,V>> implements Map<K, V>{
    //...I cannot seem to specify that the type for Base must be a Map<K, V>.
    I've thought about containing and delegating, but really Concrete IS-A Base and Concrete IS-A Map.
    Am I missing something about inheritance and generics?
    Any suggestions?

    James,
    Based on your previous posts I think you understand generics as well as I do, and in some aspects, probably better.
    I was trying to capture my thought processes (and that is quite hard since mostly this happens sub-consciously - its quite hard to drag it up into consciousness then document it, but the effort was worthwhile for me and hopefully for others as well).
    In this particular case, E is Map<K,V>, but there could be all sorts of relationships between the type variables, the idea is to identify these and back substitute them, slowly getting rid of type variables until you can't get rid of any more. The ones you are left with are the ones that need to be type parameters.
    take the other post from yesterday
    http://forum.java.sun.com/thread.jsp?thread=554360&forum=316&message=2719355
    as another worked example...
    from
    "And I'm trying to create a special generic container (List) which would only take elements that
    implement the Keyable interface above. For example:
    public class ListOfKeyables <E extends Keyable> extends AbstractList<E>{..."
    and
    "Now, besides standard List methods that use type varable 'E' in their definitions, I would also
    like to have a special method like this:
       public E getByKey(Object key)   {   ... "
    I would start with (ignoring their "E extends Keyable" suggestion, its too premature for that).
    public class ListOfKeyables < ???? > extends AbstractList<E> {
        public E getByKey(Object key) { ... }
    } but "only take elements that
    implement the Keyable interface" suggests replacing E with Keyable<K> thus
    public class ListOfKeyables < ???? > extends AbstractList<Keyable<K>> {
        public Keyable<K> getByKey(Object key) { ... }
    Note In this case the substitution getting rid of E introduced another type variable (K), thats OK, its still a step toward a solution.
    Then the original poster said "But I would like to constrain the 'key' argument in this method to be of type that is specified as a type parameter to the Keyable interface"
    So after implementing this requirement we have
    public class ListOfKeyables < ???? > extends AbstractList<Keyable<K>> {
        public Keyable<K> getByKey(K key) { ... }
    }At this point there is no more substitutions or requirements to fulfill.
    So we look through and see what type variables are still unresolved. These (in this case there is only one K), are then the type parameters of the class, and thus we have what I suggested in that post
    public class ListOfKeyables <K> extends AbstractList<Keyable<K>> {
        public Keyable<K> getByKey(K key) { ... }
    }As a final step, we need to look at the type parameters and decide if they need any constraints (K extends something), These might come from some use of the type parameter ( such as if Keyable constrained its K parameter, we would need to do the same), or from the application requirements. But in this case, there are not any.
    At a certain level of abstraction, this process is not a whole lot different to the process you use when working out what parameters a method or constructor needs (and that process also tends to happen below the consciusness threshold).
    In really simplistic terms, the answer to both "what parameters do I need" questions is "all the ones you can't get from somewhere else or derive from the ones you already have".
    Bruce

Maybe you are looking for

  • Memory for Km266

    Can I install PC2700 and PC2100 DDR modules on this board.I have 1 PC2100 128mb and found PC2700 256mb module to add to it can it be done?

  • Swf not working in IE 8, but working in firefox, chrome...

    I have just made a website (www.doneanddone.co.nz), and I have two swf. One sound swf and one video swf but none are loading in IE? Anyone know what wrong?

  • How to setup Datasource to use data triggers in Data Template

    hi all, Pls. let me know the process how to setup dataSourceRef that has to be mentioned in the data template tag for making use of various data triggers? I have packaged function which will create a temporary table that I am using in my main query.

  • Magic Chart affects the title of a slide

    In Keynote, I have a presentation where I've inserted an interactive bar chart on to a slide. I've used the Magic Chart animation to the chart and, whilst it works well, it's affecting part of the Title of that slide. Each of my titles has a border s

  • Image creating performance

    Hi, I have a problem with image creation and J2ME(midp stuff) when I open(create) an image that's more than 1024x768 pixels the phone runs out of memory even if the file is relatively small like 200k, if the image is 1024x768 or less than I can open