This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "New to Java - Inheritance - polymorphism question" Watch "New to Java - Inheritance - polymorphism question" New topic
Author

New to Java - Inheritance - polymorphism question

beth ana
Greenhorn

Joined: Jul 07, 2004
Posts: 11
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

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.

(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

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!?

sev
 
 
subject: New to Java - Inheritance - polymorphism question
 
Similar Threads
Help!!, other Dan Chrisholm's question
Method Overloading
Inheritence question
Import
Program on OOP