This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New to Java - Inheritance - polymorphism question

 
beth ana
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Below is my scenario!

I am doing a code refactor for constant variables declared in two separate A.java and B.java which are to be used in C.java.
If condition is true use the constants from A.java or Else use the constants from B.java.
So, I thought I could do below



The above code when executed prints "A". My question is without changing the reference variable 'a', can I print the result
A, B. If not possible, What is the approach suggested?

Edited by Corey McGlone: Added CODE Tags
[ July 14, 2004: Message edited by: Corey McGlone ]
 
David Ng
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given A a = new B();

If you want to access the s1 in B, you need to cast it, i.e.

(B(a)).s1

You can also add a getStr method in both class A and B:

String getStr() { return s1; }

In class C, instead of using a.s1 and (B(a)).s1, you can just say:

a.getStr()
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm moving this to Java in General (Intermediate).
 
unni krishna
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have Polymorphism only for functions and not for variables.
The variable value got depends on the type of the variable and not
the content.
 
sever oon
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These "constants" are not constant!

You have a set of variables, like x, y, z. If condition 1 is met, then x=5, y=6, and z=7. If condition 2 is met, then x=2, y=3, z=4 (for example).

I ask you: if the values of x, y, and z can change, why are you interested in dressing them up as constants!?

sev
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic