Static Elements and Inner Class

  • Eclipse: Oxygen
  • Java: 1.8

Static Elements:

Java allows you to access static members, static members are class level and can be accessed directly without any instance. For example. The static keyword means that the variable or function is shared among all the instances of that class since it belongs to the type, not to the real objects themselves.

The implementation of a static variable is shown here. The basic concept of a static variable is that it has a single reference variable.

In this way, the utilization of such variables should be possible to keep up a basic count of created objects or objects that access a class.

Example

Output

Current variable value: 0

Current variable value: 1

Current variable value: 24

Static Inner Class

We have seen the inner classes. The inner classes can access the outer variables. The static inner class can only access static members. Hence the non-static members when tried to access give an error.

A static class in Java, created within a class is called a static nested class. It is unable to access non-static data methods and members. It can be accessed by an outer class name. You can access the static data members of the outer class, including private ones.

In the following example is demonstrating static inner class would not compile because the static inner class tries to access the non-static member of the outer class that is not permitted.

So, to compile and execute the following code just add static method and you will get the following output.

Output

Testing inner class method.

0

Here the properties of the inner static class are shown and also how they can access the outer class variables and methods is shown.

Output

Value of inner class variable: 0

Testing inner class method.

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu