Quantcast
Viewing latest article 1
Browse Latest Browse All 15

Answer by Sahil Gupta for Static nested class in Java, why?

  1. JVM knows no nested classes. Nesting is just syntactic sugar.

    Below images shows Java file:

    Image may be NSFW.
    Clik here to view.
    enter image description here

    Below images show class files representation of the java file :

    Image may be NSFW.
    Clik here to view.
    enter image description here

    Notice that 2 class files are generated, one for parent and another for nested class.

  2. Non-static nested class' objects have access to the enclosing scope. That access to the enclosing scope is maintained by holding an implicit reference of the enclosing scope object in the nested object

  3. Nested class is a way to represent the intent that the nested class type represents a component of the parent class.

    public class Message {private MessageType messageType; // component of parent classpublic enum MessageType {    SENT, RECEIVE;}}class Otherclass {public boolean isSent(Message message) {    if (message.getMessageType() == MessageType.SENT) { // accessible at other places as well        return true;    }    return false;}}
  4. private static nested class represents Point#3 & the fact the nested type can only be the subcomponent to the parent class. It can't be used separately.

    public class Message { private Content content; // Component of message class private static class Content { // can only be a component of message class  private String body;  private int sentBy;  public String getBody() {     return body;  }  public int getSentBy() {     return sentBy;  }}}class Message2 {  private Message.Content content; // Not possible}
  5. More details here.


Viewing latest article 1
Browse Latest Browse All 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>