Skip to content
Fix Code Error

Java inner class and static nested class

March 13, 2021 by Code Error
Posted By: Omnipotent

What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?

Solution

From the Java Tutorial:

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass outerObject = new OuterClass()
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

see: Java Tutorial – Nested Classes

For completeness note that there is also such a thing as an inner class without an enclosing instance:

class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}

Here, new A() { ... } is an inner class defined in a static context and does not have an enclosing instance.

Answered By: Martin

Related Articles

  • Why are you not able to declare a class as static in Java?
  • next js with redux and reselect
  • TypeScript metadata reflection references other…
  • How to merge multiple intersecting polygons
  • Getting hold of the outer class object from the…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • What is the scope of variables in JavaScript?
  • Updating a model w/ Backbone.js + Rails not working…
  • Data flow in Polymer Topeka example
  • After a little scroll, the sticky navbar just is not…
  • Unable to run Robolectric and Espresso with a…
  • How do I make it so my bot doesn't send "role given"…
  • Aurelia ValueConverter fromView confusion with multi-select
  • PHP parse/syntax errors; and how to solve them
  • Reference - What does this regex mean?
  • Cannot get body from DELETE request with Slim Framework
  • Ember.js: Passing arguments to render helper
  • Jetpack Compose and Hilt Conflict
  • Examples of GoF Design Patterns in Java's core libraries
  • Eclipse will not start and I haven't changed anything
  • What does "Could not find or load main class" mean?
  • loading indicator does not show when the page route changes
  • Vue order list view
  • How do I include certain conditions in SQL Count
  • Usage of __slots__?
  • VueJS: Fetch data before and after loading a component
  • How can I resolve Web Component Testing error?
  • What is the purpose of the "role" attribute in HTML?
  • org.hibernate.MappingException: Could not determine…
  • Reference — What does this symbol mean in PHP?
  • Add Sub categories to y axis on highcharts
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Using useEffect and useContext while fetching data
  • Get the value from select form in EmberJS and ember-data
  • Creating instances of Ember models not attached to a store
  • jQuery Mobile: document ready vs. page events
  • data.table vs dplyr: can one do something well the…
  • PHP - Indirect modification of overloaded property
  • MySQL join with where clause
  • When I'm testing a web app by JUnit and Mockito I…
  • org.gradle.api.tasks.TaskExecutionException:…
  • How should a model be structured in MVC?
  • SQL Server query to find all permissions/access for…
  • How to handle Vue 2 memory usage for large data (~50…
  • What are the default access modifiers in C#?
  • How to prevent scrolling the whole page?
  • Set the local state using useEffect on Redux prop change
  • How to do the equivalent of pass by reference for…
  • SecurityException: Permission denied (missing…
  • aurelia search filtering using a computed is causing…
  • For-each over an array in JavaScript
  • Backbone routing with subviews
  • How to filter a RecyclerView with a SearchView
  • Difference between DTO, VO, POJO, JavaBeans?
  • Difference between Role and GrantedAuthority in…
  • How can I access and process nested objects, arrays or JSON?
  • How to get collection from firestore and set to vuex…
  • Vue JS: how bind an checkbox with related select in…
  • Execution failed for task…
  • REST API - Is it allowed to use different…
  • ClassNotFoundException:…
  • Best way to communicate between instances of the…
  • Smart way to truncate long strings
  • Implementation of user defined array on stack and/or…
  • Vue 2 - How to select the correct option after the…
  • Android- Error:Execution failed for task…
  • Neither BindingResult nor plain target object for…
  • Django queryset to string does not return the string…
  • Nested routing in next js
  • Trouble raising an exception using try and except
  • How to extend and merge a list of objects with…
  • What's the difference between eval, exec, and compile?
  • What's the difference between including files with…
  • What does this symbol mean in JavaScript?
  • Vue component returning multiple table rows
  • Discord.JS, How to use one discord button to allow…
  • How do I change the default port (9000) that Play…
  • What's the difference between Instant and LocalDateTime?
  • VueJS role based authentication with router
  • Creating a singleton in Python
  • @HostBinding and @HostListener: what do they do and…
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Jquery fadeToggle Trouble
  • How do JavaScript closures work?
  • ember.js: How to initialize a controller with…
  • Spring Boot with ElasticSearch in Groovy: WebClient…
  • Vue-auth conditionnal redirect after login and role…
  • Difference between `constexpr` and `const`
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • What is a NullReferenceException, and how do I fix it?
  • ERR_TOO_MANY_REDIRECTS for localhost
  • Can't get template to display using backbone.js and…
  • Python Variable Declaration
  • Laravel Livewire Multiple Category Filter not Working
  • Database development mistakes made by application developers
  • RestHeart ACL - User access controls for databases
  • Call a function (with parameters) inside a v-for…
  • How can I query a value in SQL Server XML column
  • HQL Responding with…
  • How to convert java.util.Date to java.sql.Date?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to include js file in another js file?

Next Post:

How to get first character of string?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error