Paidenwaffle
Paidenwaffle

Reputation: 196

How can I access an attribute from a child class when the parent class is the reference type and passed through a method?

First of all I'm sorry for the wordiness of the question, I am unsure how to ask, but I can explain it better.

I have a parent class and 2 child classes, only one is relavent for the example

public abstract class AudioFile{ //parent
blah blah blah
} //end class AudioFile

public class MP3File extends AudioFile{
private int bitRate; //unique to MP3File class 
} //end class MP3File

Now say I have an MP3File object but its referencing AudioFile

public class Driver{
... // pretend main exists
AudioFile file = new MP3File();
file.setBitRate(100); //pretend method exists

edit(file); 

private void edit(AudioFile audio)
{
 //how would I edit the bit rate?
} //end method edit

} //end class Driver

Upvotes: 0

Views: 1001

Answers (1)

arcy
arcy

Reputation: 13133

The real answer to your question is "don't do this".

MP3File is an extension of AudioFile; that is supposed to mean that an MP3File object is a special case of an AudioFile object, and the only things that are true of MP3File are specific to MP3 files.

Your edit method takes an AudioFile as a parameter. AudioFiles, according to your example, do not have bitRate parameters.

If you are able to cast the parameter passed into edit to an MP3File, it would still be a bad idea. That means the method is dealing with an MP3File object, and it should not assume that any AudioFile object passed to it can be cast to MP3File.

Upvotes: 1

Related Questions