Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

COMP 274<?xml:namespace prefix = o ns = \"urn:schemas-microsoft-com:office:offic

ID: 3531626 • Letter: C

Question

COMP 274<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Week 2 Homework Assignment

Reading

Lecture

Chapter 8: Objects and Classes
Sections 8.3, 8.5, 8.7, 8.8, 8.9, 8.10, 8.11

Chapter 10: Thinking in Objects
Sections 10.4, 10.5, 10.7, 10.11

Chapter 11: Inheritance and Polymorphism
Sections 11.2, 11.3, 11.4, 11.7, 11.8, 11.9, 11.13, 11.14

Create a Word document containing the answers to all the problems given below.

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote