void showP(Person p) {print(p)} void showO(Object o) {print(o)}what if we do:
Person me=new Person(...); showP(me); // 1 showO(me); // 2ans: both lines will output exactly the same result. The "showO" method doesn't need to know about the "Person" class and could have been written before "Person" was ever invented
class Window { pub void minimize() } // in a program that has an array of Windows (which might actually // be subclasses of windows): for (i=0; i<numWindows; i++) { window[i].minimize(); }Note that if/when we ever invent a new type of Window which does something special when it's minimized, the above loop will still work fine.
public class Tiger extends Animal { ...Whenever you write a new class you always extend another class, even if you don't use the "extends" keyword. Why is this? - Because any class that doesn't explicitly extend has an implicit "extends Object"
There is no "right" answer as to how to split functionality between base and subclass. You do need to think carefully about what methods you define where. It's very hard to change a base class once it's been written - why? because people might have written code based on the initial implementation
// an "AudioInputStream" is a subclass of "InputStream" void myMethod(InputStream myInputStream) { myInputStream.reset(); // 1 AudioFormat af = myInputStream.getFormat(); // 2 } . . AudioInputStream a; myMethod(a);We can pass "a" to the method, and line "1" will work, because "reset" is a method defined by "InputStream". But the compiler will refuse line 2 because it doesn't know for sure that myInputStream is an AudioInputStream, even though in the code above we know it is.
To make line 2 work we'd need:
if (myInputStream instanceof AudioInputStream) { AudioFormat af = myInputStream.getFormat(); // 2 }
public abstract class Garage { . . . }What difference does this make?
Person me = new Person("nick",21); // 1 System.out.println("the person is " + me); // 2displays something like:
the person is nick, who is 21 and was created on xxxxx
Can you come up with a way to change the code at "2" (you can change the line or add extra lines, but not change any of the "Person" class methods) so that the output will now be:
the person is Person@1bab50ai.e. bypass the "Person.toString()" method?
int x = 123; System.out.println("x is -->" + x + "<--");will by default output:
x is -->123<--What can you do (if anything) to make the integer value be padded up to eight digits with leading zeroes? i.e.:
x is -->00000123<--