• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Polymorphism? Quick Question

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have this class:


and



both with irrelevant information.

Question... I have a SurgeProtector class in which I add a certain amount of ElectronicDevices to the SurgeProtector. Within SurgeProtector I have set up an array that has a limit of 20 ElectronicDevices that can be added to the SurgeProtector. When adding 20 random ElectronicDevices, how do I count the amount of Appliances that are added.

(other items that can be added are TV, Refrigerator, CellPhone. Each of which extend ElectronicDevice) How do I tell how many of each device is added into SurgeProtector???

Thanks for any and all help!
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matt Wilde wrote:how do I count the amount of Appliances that are added.



Iterate over the array, and for each element, check if (element instanceof Appliance). However, if you need to do that, you're ignoring the most powerful part of Java's polymorphism, and you probably shouldn't put all these things in the same array.

Although it depends on what you're doing. If you're doing


then, yeah, you probably have a design problem.

If, on the other hand, you just want to report on how many of each class there are, then you can check each object's class name, and create a Map<String, Integer> to count instances by class.
 
Matt Wilde
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you so much that helped a lot!

my abstract method ElectronicDevice has a method getCurrentWattsPerHour().

I am trying to run that method from SurgeProtector by using

ElectronicDevice ED = new ElectronicDevice(); but i am getting an error "Cannot instantiate the type ElectronicDevice"

last question
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matt Wilde wrote:Thank you so much that helped a lot!

my abstract method ElectronicDevice has a method getCurrentWattsPerHour().



Okay, makes sense. After all, it makes sense to query any electronic device for its power consumption. (Note, however, that the unit "watt"(⇐click) is a measure of energy per unit time--1 watt = 1 joule / sec., so the "PerHour" part makes no sense.)

I am trying to run that method from SurgeProtector by using

ElectronicDevice ED = new ElectronicDevice(); but i am getting an error "Cannot instantiate the type ElectronicDevice"



If you think about what you're saying, you should realize it makes no sense, even before you get to the fact that an abstract class cannot be instantiated. Nowhere in that code is there anything about SurgeProtector. So how would Java know that you want to work with a SurgeProtector?

So, given that, what do you think you might need to do to change that code so it makes sense? (Which, coincidentally, will also allow it to compile.)
 
Matt Wilde
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well thats the thing, I want to use the SurgeProtector's method to retrieve "getCurrentUsagePerHour()" [i know it doesnt make sense ha] from the ElectronicDevice class.

We just did Polymorphism in class today and I am so incredibly stumped!!!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matt Wilde wrote:Well thats the thing, I want to use the SurgeProtector's method to retrieve "getCurrentUsagePerHour()"



If SP implements its own version of that method then as long as you have an SP object (and as long as the method is not private, static, or final in the parent class), then you'll get SP's version, even if the reference is of the parent class type. And if it doesn't override that method, then you'll get the version inherited from the parent class (or grandparent, or great grandparent, etc.).

On the other hand, if you have a SurgeProtector object, and it does override that method, but you want to call the parent's method anyway (other than from within SurgeProtector's own version of that method), then you have a design flaw.

Run this, and see if that clears things up.

 
Matt Wilde
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what would you do if your Child class was also abstract?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matt Wilde wrote:what would you do if your Child class was also abstract?



Then you wouldn't be able to instantiate it. You'd have to instantiate a concrete subclass.



I leave it as an exercise for you to change my sample code and see what happens.

Is your SurgeProtector class abstract?
 
Matt Wilde
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My SurgeProtector is not abstract. I am only allowed to change the contents of SurgeProtector which is completely do-able (for many people).

SurgeProtector is on its own.

The higharchy for Electronic Device is:

abstract Electronic Device
abstract Appliance extends ElectronicDevice --------- CellPhone extends Electronic device
Fridge extends Appliance
TV extends Appliance

ElectronicDevice has a getCurrentWatts method that is overridden by its children.

Must I create new Objects in SurgeProtector for each of the children and run their getCurrentWatts method and add all those to get the total watts?

such as:

ElectronicDevice c = new CellPhone(wattsUsedPerHour,hoursUntilFullCharge);
double celluse = (double) c.getCurrentUsagePerSecond();
Appliance f = new Refrigerator(wattsUsedPerHour);
double fridgeuse = (double) r.getCurrentUsagePerSecond();
Appliance t = new TV(wattsUsedPerHour);
double tvuse = (double) t.getCurrentUsagePerSecond();
usage = celluse+tvuse+fridgeuse;

If you a pressed for time you need not respond you have done plenty and I am so grateful! I will attempt to edit your sample code!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matt Wilde wrote:
Must I create new Objects in SurgeProtector for each of the children and run their getCurrentWatts method and add all those to get the total watts?



Oops. I was thinking SurgeProtector was a subclass of Electronic device and you were trying to get its power usage.

But you're trying to find the power consumed by each device connected to the protector, yes?


such as:

ElectronicDevice c = new CellPhone(wattsUsedPerHour,hoursUntilFullCharge);
double celluse = (double) c.getCurrentUsagePerSecond();
Appliance f = new Refrigerator(wattsUsedPerHour);
double fridgeuse = (double) r.getCurrentUsagePerSecond();
Appliance t = new TV(wattsUsedPerHour);
double tvuse = (double) t.getCurrentUsagePerSecond();
usage = celluse+tvuse+fridgeuse;



Right.

Or, your protector might have an array or List of ElectronicDevices, and you might add any arbitrary combination of devices, and then you'd just iterate over the array, calling that method on each element and adding the result to a running total.

Note, however, that it doesn't appear that each class needs to override the usage method. If you're just passing the value into the constructor, storing it, and then returning it in the method, that should all just be in the parent class.

If you a pressed for time you need not respond you have done plenty and I am so grateful!



You're quite welcome, but don't worry about me. When I get bored, tired, or busy, I disappear.

I will attempt to edit your sample code!
 
Matt Wilde
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
right, so i have a method in SurgeProtector:



Then later in my getCurrentUsage method i have:


Still, Obviously it doesnt work, and it seems like all I am doing is stepping through a blank array.........
 
Matt Wilde
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Forgot to mention that I had an instance variable at the beginning of the class

ElectronicDevice[] ED;
 
Marshal
Posts: 79180
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

I have added code tags to some of your code and you can see how much better it looks Don’t use tabs for indenting.
That use of instanceof looks even more disastrous than Jeff was suggesting. What will happen when you have this class?Or VacuumCleaner? Or Radio? Think what will happen to that method? That use of instanceof looks like really bad design to me.
I can think of at least two ways to count
  • 1: Have a static count field in each class (note, this must be repeated in each class so as to hide the superclass version).
  • 2: Use a Map.
  • The static count version has the drawback that you have to hide the field by repeatedly declaring it in each class. Also, you have to organise things so you get 0 the second time you interrogate an instance of a class, as should be obvious. There is lots about Maps in the Java Tutorials, with a similar counting example. In this case, you would use the Class<?> object, which you can get from the getClass() method every class inherits from Object, as a key.
     
    Matt Wilde
    Ranch Hand
    Posts: 34
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thank you SO MUCH Jeff and Campbell! I managed to get rid of about half the code as Campbell said I had many design flaws. And thanks Jeff for walking me through the basics!

    All I had to do:
    Loop through and add ElectronicDevice e into the ED array.
    For CurrentUsage just loop through the array and run the getCurrentUsage for each instance of ElectronicDevice in the array.
    use the above method for getNumDevices for TV/Appliance/CellPhone/ etc.

    anyway. I understand it! Thanks coderanch
     
    Campbell Ritchie
    Marshal
    Posts: 79180
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    You’re welcome
     
    Jeff Verdegan
    Bartender
    Posts: 6109
    6
    Android IntelliJ IDE Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    You're welcome.
     
    pie. tiny ad:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic