my dog learned polymorphism
The moose likes Java in General and the fly likes New to Java - Inheritance - polymorphism question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "New to Java - Inheritance - polymorphism question" Watch "New to Java - Inheritance - polymorphism question" New topic

New to Java - Inheritance - polymorphism question

beth ana

Joined: Jul 07, 2004
Posts: 11
Below is my scenario!

I am doing a code refactor for constant variables declared in two separate and which are to be used in
If condition is true use the constants from or Else use the constants from
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

Joined: May 11, 2004
Posts: 12
Given A a = new B();

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


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:

Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
I'm moving this to Java in General (Intermediate).

SCJP Tipline, etc.
unni krishna
Ranch Hand

Joined: Jul 14, 2004
Posts: 39
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.

Software Engineer (SCJP)<br />USTechnology, CA
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
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!?

I agree. Here's the link:
subject: New to Java - Inheritance - polymorphism question
It's not a secret anymore!