• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubts about final and private methods  RSS feed

 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I've a few doubts about inheritance and override when using 'final' and 'private' keyword.

So,

1- A final class can't be inherited.
2- A final method inside a public class can be inherited but not overridden.
3- A private method can't be inherited, and so it can't be overridden.

Is this right?
 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ivan Addeo wrote:1- A final class can't be inherited.

More correctly, a final class can't be extended. Thus, it is impossible for any class to inherit anything from a final class.

2- A final method inside a public class can be inherited but not overridden.

Correct.

3- A private method can't be inherited, and so it can't be overridden.

Correct.

This is from the JLS https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8
The JLS folks wrote:A class C inherits from its direct superclass and direct superinterfaces all abstract and non-abstract methods of the superclass and superinterfaces that are public, protected, or declared with default access in the same package as C, and are neither overridden (§8.4.8.1) nor hidden (§8.4.8.2) by a declaration in the class.


 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks

So,

1- If I've public final class A, I can't say class B extends A.

2 - If I've a public class A with a final method, I can say class B extends A, but the method can't be overridden.
 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, those are both correct.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh and,

3- If I've class A with some methods and one is private. I can say that class B extends class A but the single method marked private will not be inherited.

Right?
 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Clear, thanks again
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!