1.We can call a method in the same class using an in instance of that class
but if i call work() method on 'b' reference i should get a compiler error. why cant JVM find work() method inside class A using an instance of class B. but if i extend class A with class B my object gains the ability to call work() method. im really curious how it works, so i want a detailed explanation as to what goes inside JVM . which brings me to my next question
2.Does each class get its own stack and heap? if the answer is yes, what happens when you inherit one class with another, do the two stack/heap become one? Is that how my object(1st question) gain the ability to call work() method.
When you say , you are actually inheriting the methods of class A, so in that case you are not going to get an error when calling method work() on b reference.In your case, the two classes are not related hence you are going to get a compiler error.In other words, the code in class A is not visible from b reference
1. Classes A and B don't have anything to do with each other in your code example. If you try to call a method defined in class A on an instance of class B, then that is ofcourse not going to work. When class B extends class A, then class B inherits all the (non-private) methods of class A, so then you can use those methods in an instance of class B. See Inheritance in the Java Tutorials for a more detailed explanation of what inheritance means and how it works.
2. No, each class does not get its own stack and heap. Each thread has its own stack, and there's only one heap that is shared by all threads. Stack and heap have nothing to do with classes and inheritance or finding methods.
Thank you all for answering my question, but im not sure if i got the answer i was expecting, someone told me that an object finding a method has something to do with virtual method table, which i dont fully understand. i just wanna know how an object receives this information" hey you're only allowed to call methods in the same class that you belong to". when an object calls a method how does it know what class the method is in. hope someone can help me now.
You would appear to have two questions there.
When the compiler goes through the code, it checks that the method requested is available in that class. If it is not available in that class, then it checks the superclass, and keeps going until it finds java.lang.Object. If the method hasn't been found by then, there is an error.
When the JVM executes an instance method, it finds the Class<T> Object from the instance being used at the moment. Then it looks in that Class<T> object for the requested method, and if it doesn't find it, it can find the superclass Class<T> object because all .class files have an "extends" declaration. The first method found is executed, so you get polymorphism.