Can someone demonstrate an example of a simple program where changing the access of one method from private to public in a working program will cause no compilation errors but only leads to the program behaving differently?
Also when will adding a new private method cause either compilation errors or lead to the program behaving differently?
This comes into play with inheritance. A subclass can have a method with the same signature as a private method in its parent class, but not override it.
public class Scratchpad {
public static void main(String[] args) {
new Sub().doSomething();
}
}
class Super {
public void doSomething() {
System.out.println(computeOutput());
}
private String computeOutput() {
return "Foo";
}
}
class Sub extends Super {
public String computeOutput() {
return "Bar";
}
}
If you run this as-is, you get Foo
. If you change Super#computeOutput()
to public
, you get Bar
. That's because Sub#computeOutput()
would now override Super#computeOutput()
.
Also when will adding a new private method cause either compilation errors or lead to the program behaving differently?
Borrowing from Mark's code, if you add the private method to Sub
, the following will not compile because the visibility of doSomething()
has been reduced.
class Super {
public void doSomething() {
System.out.println("Foo");
}
}
class Sub extends Super {
private void doSomething() {
System.out.println("Harr!");
}
}
Also when will adding a new private method cause either compilation errors or lead to the program behaving differently?
If the private method added is more specific that the previous one, you can adjust program behaviour. The example below prints "bar" unless you add (uncomment) the other method at which point it prints "foo".
public class Test {
public static void main(String[] args) throws Exception {
String foo = "hello";
methodOne(foo);
}
// private static void methodOne(String args) {
// System.out.println("foo");
// }
private static void methodOne(Object arg) {
System.out.println("bar");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With