Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing access to methods without a compilation error

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?

like image 419
user3363135 Avatar asked Feb 14 '23 05:02

user3363135


2 Answers

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().

like image 82
Mark Peters Avatar answered Mar 03 '23 15:03

Mark Peters


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");
  }
}
like image 45
Duncan Jones Avatar answered Mar 03 '23 14:03

Duncan Jones