I’m a newcomer of OOP, so I has one silly question about when a class extends another class.
Here my example:
public class Test {
public Monitor getMonitor(){
return new LCD();
}
class LCD extends Monitor { NO-ERROR
class LCD { ERROR at line `return new LCD`
//some other method or function not in Monitor Class. Example:
boolean isSamsung;
public LCD whatkindLCD(){
}
}
}
I have one question for above code : because LCD is extended from Monitor and LCD has some other properties/methods that Monitor does not. So, LCD is child of Monitor, right ?
It means you try to put a “big box” to a “small box”. So, why when I return new LCD, Eclipse don’t notice error as when I just use class LCD {.
Thanks 🙂
Understand Inheritance as a “is a” relationship. Here is a simple example I used to understand inheritance during my novice years.
Compiler looks for reference type before calling any operations on it.
em.getBonus() doesn’t work because Employee doesn’t have a bonus method.
But using a cast we can make it work.
((Manager)em.)getBonus()
Reason why compiler looks for the reference type before calling any operation on it is as follows:
Manager[] managers = new Manager[10];
It is legal to convert this array to an Employee[] array:
Employee[] staff = managers; // OK
Sure, why not, you may think. After all, if manager[i] is a Manager, it is also an Employee. But actually, something surprising is going on. Keep in mind that managers and staff are references to the same array.
Now consider the statement
staff[0] = new Employee(“John Eipe”, …);
The compiler will cheerfully allow this assignment.
But staff[0] and manager[0] are the same reference, so it looks as if we managed to smuggle a mere employee into the management
ranks.
That would be very bad — calling managers[0].setBonus(1000) would try to access a
nonexistent instance field and would corrupt neighboring memory.
To make sure no such corruption can occur, all arrays remember the element type with
which they were created, and they monitor that only compatible references are stored into
them. For example, the array created as new Manager[10] remembers that it is an array of
managers. Attempting to store an Employee reference causes an ArrayStoreException.