Consider the following Java class that uses private fields to hide data. What will be printed when the main method runs?
public class Person { private String name = "Alice"; private int age = 30; public String getName() { return name; } public void setName(String newName) { name = newName; } public static void main(String[] args) { Person p = new Person(); System.out.println(p.name); } }
Private fields can be accessed directly from main inside the same class using an instance reference.
The name field is private, but access from within the same class (even static main via instance p) is allowed. It prints "Alice".
Given the class below, what will be printed when the main method runs?
public class BankAccount { private double balance = 1000.0; public double getBalance() { return balance; } public static void main(String[] args) { BankAccount account = new BankAccount(); System.out.println(account.getBalance()); } }
Private fields can be accessed inside the class. Public methods can expose them safely.
The private field balance is accessed via the public method getBalance(). This is the correct way to read private data from outside the class.
Look at this Java class. The setAge method tries to update the private field age. Why does the age not change after calling setAge(40)?
public class Employee { private int age = 25; public void setAge(int age) { age = age; } public int getAge() { return age; } public static void main(String[] args) { Employee e = new Employee(); e.setAge(40); System.out.println(e.getAge()); } }
Check the difference between the parameter and the field names inside the method.
The method parameter age has the same name as the field age. The assignment age = age; assigns the parameter to itself, not the field. To fix, use this.age = age;.
Choose the correct code snippet that declares a private integer field count and a public method getCount that returns it.
Remember Java syntax for access modifiers and case sensitivity.
Option D correctly declares a private field and returns it using this.count. Option D is also valid but option D is preferred for clarity. Option D has invalid modifier order. Option D uses wrong case Count.
Given the following two classes in the same package, how many objects can directly access the private field secret of SecretBox?
public class SecretBox {
private String secret = "hidden";
}
public class Spy {
public void tryAccess() {
SecretBox box = new SecretBox();
System.out.println(box.secret);
}
}Recall what private means in Java regarding access from other classes.
Private fields are accessible only within the class they are declared in. No other class, even in the same package, can access them directly.