Accessing Members of class:
Java enforces you to encapsulate each and every attribute
and methods inside a template called class (can be Abstract class, interface
etc) that means these attributes and methods are not visible to the outside world.
How do we access these variables or methods if it is
encapsulated?
We will answer this question latter in this discussion.
Access levels for class members:
Class level access (Full Access):
- Each and every members of a class are completely visible within the same class.
- In fact there is no way to hide any of the members from being used by the other members of same class.
Inheritance (Limited Access):
- If you want to use any of the variable or method which is a member of other class you may extend that class.
- Each and every public, protected and default (same package) member of the super class can be called in sub class.
- In fact all of these members become part of subclass.
Create an Object (has-a / uses-a relationship):
- Declare the object as class variable (has-a relationship).
- Declare the object as local variable (uses-a relationship).
- Through this object one can access all the non private members of that class using dot operator.
- Eg :
Declare that member as static:
- As soon as you declare a member as static it becomes global.
- There is no need of creation and object or inherit the containing class.
- Just use the class name and dot operator.
What does static keyword do?
- It makes the members (methods and variables) of a class independent from object creation and puts these things in global memory at runtime.
- That means same copy of static variable and method are shared by all objects of that type at runtime .object does not receive a separate copy of static members at runtime.
- Eg: Think in this way-
Question: How does you program starts execution?
Answer: Your answer is main method.
Question: But how does the JVM gets access to the main
method without creating object of the class which contains main().
v
Ok fine JVM knows the prototype of main method
so it searches for the main() method prototype and starts execution .
v
But any how JVM has to gain access to the main
method which is residing inside any of class in application isn’t it?
v
As we know everything in java resides in a class
so JVM should not have access to a class member without creating object of that
type then how does it starts execution.
Answer: Because main() is static and as we dont need to create the object of the class to access any of its statics members/methods JVM does not find any issue on executing the main() method.
No comments:
Post a Comment