Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This question is flawed - an extended <code>Object</code> is always an instance of its super class.</p> <p>In your example, the following is valid...</p> <pre><code>public class PartialFile extends File{ // methods } PartialFile partFile = new PartialFile(); // do operations on partFile File file = partFile; // do operations on file </code></pre> <p>Because <code>PartialFile</code> extends <code>File</code>, you don't really need to 'turn it into its super class' - it already is an instance of the super class.</p> <p>You can think of the <code>PartialFile</code> object as being a <code>PartialFile</code>, a <code>File</code>, an <code>Object</code>, and any other classes that it extends, all at the same time. You don't need to turn it between these different class types - just use it directly. For the above code, if you want to call the <code>File.rename()</code> method, both the following statements will do the same thing...</p> <pre><code>partFile.rename(); file.rename(); </code></pre> <p>You don't need to change the <code>partFile</code> into a <code>file</code> to use the methods of the <code>File</code> object - just use them directly, as the Java VM knows that a <code>PartialFile</code> is also a <code>File</code>.</p> <p>You can't really change a sub-type to be its super type - the Java VM will always know what type it really is - but you can trick it. If you use the following code...</p> <pre><code>PartialFile partFile = new PartialFile(); // do operations on partFile File file = partFile; // do operations on file </code></pre> <p>and then only every use <code>file</code> instead of <code>partFile</code>, you won't be able to use any of the <code>PartialFile</code> methods on it. It kinda disguises that its a <code>PartialFile</code>, but it doesn't actually convert it.</p> <p>If you do something like this...</p> <pre><code>public File createFile(){ PartialFile partFile = new PartialFile(); // operations on partFile return partFile; } File file = createFile(); // operations on file </code></pre> <p>You can create and use a <code>PartialFile</code> in the method, but when you're finished you return it as a simple <code>File</code>. Whenever you refer to this object from now on, the Java VM will pretend that its a <code>File</code>. However, technically it will always be a <code>PartialFile</code>, and it doesn't stop you casting it back into a <code>PartialFile</code> if you want to, like so...</p> <pre><code>PartialFile partFile = (PartialFile)file; // operations on partFile </code></pre> <p>So its just a disguise.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload