0

I discovered that following code compiles:

class Ideone
{
    public static void main (String[] args){
         new Ideone().m();
    }

    final private void m(){
        System.out.println("private final method");
    }

     class A extends Ideone{
        public  void method(String [] args){
           m();
        }
    }
}

and executes.

I am very wondering about this.

Can you explain why does java designers(founders) made that it works?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

0

A final method can be inherited by a sub class regardless the sub class is outside the parent class or inside the parent class. But you cannot override the final method in your subclass. If the final method is private you cannot inherit that in your subclass unless your subclass is inside the parent class (like in your example).

Prudhvi
  • 2,276
  • 7
  • 34
  • 54
0

Since you declare the method private, then final has no effect and is redundant.

Overriding a private method don't really make much sense.

It is no different then calling a private method in a class from another method in the same class (which might be public). That is something that is done often to keep code more readable and method's manageable in size.

I don't think it is a stupid question :)

Take the Builder-pattern for example. It utilizes private constructors to make sure the class is constructed the correct way. So understanding what you have available in different scope's, and why is important :)

class Ideone {
private String m;

private Ideone(String m) {
    System.out.println("Build me with: " + m);
    this.m = m;
}

public String getM() {

    return m;
}

static class IdeoneBuilder{
    String m;

    public IdeoneBuilder withM(String m) {
        this.m = m;
        return this;
    }

    public Ideone build() {
        return new Ideone(this.m);
    }

}

public static void main (String[] args){
    // new Ideone(); // will not compile
    Ideone ideone = new IdeoneBuilder()
            .withM("test").build();
}
} 

Edit: You can make the class Ideone final, and it will still work. And you are also making it impossible to subclass it. In other words, you make sure there is no other way to construct an object of your class other than using the builder (unless the use of reflection).

thomas77
  • 1,100
  • 13
  • 27