Yes indeed it will call the method from the child. This is due to a feature called dynamic method binding. Java will dynamically bind a method call to the child object furthest down the class heirarchy. So:

class ParentClass {
   public void callMethod(){
       System.out.println("The Parent");
   }
}

class ChildClass extends ParentClass {
   public void callMethod(){
       System.out.println("The Child");
   }
}

class Test {
public static void main(String[] args){
ParentClass example1 = new ChildClass();
example1.callMethod(); // will call the method in ChildClass
((ParentClass)example1).callMethod(); // will still call the method in ChildClass


ParentClass example2 = new ParentClass();
example2.callMethod(); // will call method in ParentClass, as that is the furthest child down the heirarchy in the variable example2
}
}


Hope that helps explain why.
D

Luc Foisy wrote:

If I cast an object as its superclass, then call a method that has been overrided in the child, will it call the method from the child or the superclass??
Such as:


public class TMHTTPDataObject
{
        String value = "";

        public void setValue(String _value)
        {
                value = _value;
        }

        public String getValue()
        {
                return value;
        }
}

public class TMHTTPDateField
{
        public void setValue(String _value)
        {
                value = dateConvert(_value);
        }
}

if( panelItems.elementAt(i) instanceof TMHTTPDataObject )
{
        TMHTTPDataObject temp = (TMHTTPDataObject) panelItems.elementAt(i);
        if( temp.getLinkedField().equals(_linkedField) )
        {
                temp.setValue(_value);
                break;
        }
}


Should getValue return the string straight up or the dateConverted string??


---
You are currently subscribed to jdjlist as: [EMAIL PROTECTED]
To unsubscribe send a blank email to [EMAIL PROTECTED]
http://www.sys-con.com/fusetalk





---
You are currently subscribed to jdjlist as: [EMAIL PROTECTED]
To unsubscribe send a blank email to [EMAIL PROTECTED]
http://www.sys-con.com/fusetalk

Reply via email to