Home arrow static arrow Java Programming [Archive] - Java Inheritance issue
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Java Inheritance issue
This topic has 2 replies on 1 page.

Posts:15
Registered: 3/25/04
Java Inheritance issue  
Jun 29, 2004 9:28 AM



 
I'm new to OO programing... having some doubts

For example

Super class AAA has 2 Sub class BBB and CCC
BBB has a attribute called ddd and a method getDdd()
CCC has a attribute called eee and a method getEee()

in the main program user have to select either B or C.
Then a conditional statement
if selected is B then     instantiatate AAA myObj = new BBB();else     instantiatate AAA myObj = new CCC();end if


My doubt is how can i call the method is the subclass (i.e: getDdd() or getEee)

Infact i did this
if selected is B then     myValue = myObj.getDdd();else     myValue = myObj.getEee();end if


but it is not working. Can anyone help me with this.
Thanks

 

Posts:147
Registered: 26.01.04
Re: Java Inheritance issue  
Jun 29, 2004 9:35 AM (reply 1 of 2)



 
Object myValue;if (selectedObject instanceof BBB)    myValue = ((BBB)selected).getDdd();else   myValue = ((CCC)selected).getEee(); 
 

Posts:147
Registered: 26.01.04
Re: Java Inheritance issue  
Jun 29, 2004 9:40 AM (reply 2 of 2)



 
but basically this is not good code for two reasons:
a) instanceof takes a looong time :x
b) there are better ways:

take advantage of the overriding/dynamical bindings in java:
class A {    public int getValue() { //could be declared abstract        return 0;    }} class B extends A {    int bValue = 50;    public int getValue() {        return bValue;    }} class C extends A {    int cValue = 100;    public int getValue() {        return cValue;    }} ...A myObject = SelectedObject;System.out.println(myObject.getValue()); //wil print 0 if Selected was an A-Object, 50 if it was an B-Object, 100 if it was an C-Object...
 
This topic has 2 replies on 1 page.