• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing code inside class but not in any initialization blocks  RSS feed

 
Abhay Bhatt
Ranch Hand
Posts: 64
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we write normal code inside class, but not in any kind of initialization blocks, or in any of the methods. If yes, then exactly when that code is executed, and how it doesn't make initialization blocks(instance or static or both) redundant/useless?
 
Pete Letkeman
Ranch Foreman
Posts: 906
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know, all code is either in methods (including constructors), or initialization blocks. Java is heavy on the concept of object programming and not so much on functional programming.
Are you able to provide a code sample of what you are talking about?
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, you need to be more precise.

Not being picky on question you have asked, you can't write code outside initializers or methods (including constructor).
What you can have within a class, are variables declarations along with their initializations (or without).

Of course initializers and methods need to be in a class or interface (since Java 8).
 
Abhay Bhatt
Ranch Hand
Posts: 64
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:Yeah, you need to be more precise.

Not being picky on question you have asked, you can't write code outside initializers or methods (including constructor).
What you can have within a class, are variables declarations along with their initializations (or without).

Of course initializers and methods need to be in a class or interface (since Java 8).


Thanks a lot! That's what I was looking for.
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Earlier, I wrote:Of course initializers and methods need to be in a class or interface (since Java 8).

I probably need to clarify this point, that you can't have initializers nor static nor instance within interfaces, just methods can be in interfaces. This restriction doesn't apply to regular classes.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!