-4

As far as I understand, private methods and final methods are the same. The Java compiler determines the meanings of private methods at compile time. Neither private methods nor final methods can be modified at runtime, and neither can be overridden. These similarities make it seem like private and final methods are the same. Is this true?

Resigned June 2023
  • 4,638
  • 3
  • 38
  • 49
Mdhar9e
  • 1,376
  • 4
  • 23
  • 46

2 Answers2

2

Consider the following example:

class Super {

    private void foo(){}

    final void bar(){}

}

class Sub extends Super {

    private void foo(){}

    final void bar(){}

}

You will have no problem having the foo() method, but you will get compilation issues when trying to compile the bar() method. This is because the bar() method cannot be overriden, but the foo() method is just not visible - so no overriding occurs.

You can see more answers here: Overriding private methods in Java

Community
  • 1
  • 1
Obicere
  • 2,999
  • 3
  • 20
  • 31
2

A private method is automatically final and hidden from its derived class. A final class is not hidden from its derived class. Therefore you can make a new class with the same name as the private method such as

class test {
    private void works {
    }
}
class tester extends test {
    private void works {
    }
}

but you cannot make a new class with the same name as the final method

/*----------Doesn't Work------------*/
class test {
    final void dWorks {
    }
}
class tester extends test {
    final void dWorks {
    }
}

Example and answer here : http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ309_006.htm

apkisbossin
  • 336
  • 1
  • 3
  • 16