What is the output of this Java program?
class A { public void greet() { System.out.println("Hello from A"); } } public class B { public static void main(String[] args) { A obj = new A(); obj.greet(); } }
Remember that public methods can be accessed from any other class.
The method greet() is declared public in class A. This means it can be called from class B without any access issues. So, the program prints "Hello from A".
Given two packages pkg1 and pkg2, what is the output of the following code?
package pkg1; public class Data { public int number = 42; } package pkg2; import pkg1.Data; public class Test { public static void main(String[] args) { Data d = new Data(); System.out.println(d.number); } }
Public variables can be accessed from any package if the class is imported.
The variable number is public in class Data. Since Test imports Data, it can access number and print its value 42.
Consider the following code. Why does it cause a compilation error?
class Parent { public void show() { System.out.println("Parent show"); } } public class Child extends Parent { void show() { System.out.println("Child show"); } }
Check the access levels of overridden methods.
When overriding a method, the access level cannot be more restrictive. The Parent's method is public, but Child's method is package-private (default), which is more restrictive. This causes a compilation error.
Which option contains a syntax error related to the use of the public modifier?
Check where public can be used inside methods.
You cannot declare a variable inside a method with an access modifier like public. Local variables cannot have access modifiers. Option C tries to declare public int x = 5; inside a method, which is invalid syntax.
Given the following code in two files, what will happen when compiling and running?
// File: pkg1/PublicClass.java
package pkg1;
public class PublicClass {
public void display() {
System.out.println("Visible everywhere");
}
}
// File: pkg2/DefaultClass.java
package pkg2;
class DefaultClass {
public void show() {
System.out.println("Visible only in pkg2");
}
}
// File: pkg2/TestAccess.java
package pkg2;
import pkg1.PublicClass;
public class TestAccess {
public static void main(String[] args) {
PublicClass pc = new PublicClass();
pc.display();
DefaultClass dc = new DefaultClass();
dc.show();
}
}Check the package and access levels of classes and their usage.
DefaultClass has default (package-private) access and is in the same package pkg2 as TestAccess, so it can be accessed. PublicClass is public and imported from pkg1. Both objects can be created and their methods called. The program prints both messages.
