You are on page 1of 3

Topic: Access Modifiers

// Class A is declared in a file named A.java.


package com.test.work;
public class A {
public void m1() {System.out.print("A.m1, ");}
void m2() {System.out.print("A.m2, ");}
}
// Class D is declared in a file named D.java.
package com.test.work.other;
import com.test.work.A;
public class D {
public static void main(String[] args) {
A a = new A();
a.m1(); // 1
a.m2(); // 2
}}
What is the result of attempting to compile and run the program?
Prints: A.m1, A.m2,
Runtime error occurs.
Compile-time error at 1.
Compile-time error at 2.
Topic: Access Modifiers
public class MyClass {
int calculate(int i, int j)
{
return 2+i*j;
}
public static void main(String [] args) {

int k = MyClass.calculate(5,10);
System.out.println(k);
}
}
What is the result?
70
52
Compilation error
An exception is thrown at runtime
Topic: Access Modifiers
Given the following,
1. package testpkg.p1;
2. public class ParentUtil {
3.

public int x = 420;

4.

protected int doStuff() { return x; }

5. }
1. package testpkg.p2;
2. import testpkg.p1.ParentUtil;
3. public class ChildUtil extends ParentUtil {
4.

public static void main(String [] args) {

5.

new ChildUtil().callStuff();

6.

7.

void callStuff() {

8.

System.out.print("this " + this.doStuff() );

9.

ParentUtil p = new ParentUtil();

10.

System.out.print(" parent " + p.doStuff() );

11.
12. }

Which statement is true?


The code compiles and runs, with output this 420 parent 420.
If line 8 is removed, the code will compile and run.
If line 10 is removed, the code will compile and run.
Both lines 8 and 10 must be removed for the code to compile.

You might also like