1. Can you access an instance variable from a static method? Explain why or why
ID: 3655626 • Letter: 1
Question
1. Can you access an instance variable from a static method? Explain why or why not. 2. Can you access a static variable from an instance method? Explain why or why not. 3. Consider the case where you have two classes, ClassA and ClassB, such that ClassA contains a member variable defined as ClassB myBobj. ClassB contains a constructor which takes a String parameter. ClassA provides a constructor which accepts a String parameter which is to be provided to myBobj. What needs to be done to initialize the ClassB member variable with the value from the ClassA constructor? 4. Here are some class definitions with questions that follow. public class BaseClass { // methods of BaseClass } public SomeClass extends BaseClass { // methods of SomeClass } a. SomeClass scobj = new SomeClass( ); b. BaseClass bcobj = scobj; c. SomeClass scobj2 = bcobj; d. bcobj.aMethodOfSomeClass( ); // does not exist in BaseClass A. Is statement b above legal, or is casting required? B. Statement c is trying to assign the SomeClass object referred to by bcobj to a SomeClass reference variable scobj2. What is wrong with this statement and how would you fix it. C. In statement d, a BaseClass reference is trying to access a SomeClass class method that is not part of BaseClass. Is this legal? Explain.Explanation / Answer
How does a static method access instance variables?
Static methods can not directly access any instance variables or methods. But they can access them by using their object reference. Static methods may even access private instance variables via a object reference.
public class Program {
private int count;
public Program(int ballcount){
count=ballcount;
}
public static void main(String argv[]){
Program s = new Program(99);
//System.out.println(count); //compile time error
//add(10); //compile time error
System.out.println(s.count);
s.add(10);
System.out.println(s.count);
}
private void add(int num) {
count += num;
}
}
The output result is
99
109
All private instance variables are private to its class, they can be accessed by static methods or non-static method of the class.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.