Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

New to Java - Inheritance - polymorphism question

 
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 ]
 
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()
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm moving this to Java in General (Intermediate).
 
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.
 
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
 
Of course, I found a very beautiful couch. Definitely. And this tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic