{"id":1216,"date":"2022-02-25T16:58:03","date_gmt":"2022-02-25T16:58:03","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1216"},"modified":"2022-02-25T16:58:03","modified_gmt":"2022-02-25T16:58:03","slug":"nested-and-inner-class","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/25\/nested-and-inner-class\/","title":{"rendered":"Nested and Inner Class"},"content":{"rendered":"\n<p>In this tutorial, you will learn about the nested class in Java and its types with the help of examples.<\/p>\n\n\n\n<p id=\"introduction\">In Java, you can define a class within another class. Such class is known as&nbsp;<code>nested class<\/code>. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class OuterClass {\n    \/\/ ...\n    class NestedClass {\n        \/\/ ...\n    }\n}<\/code><\/pre>\n\n\n\n<p>There are two types of nested classes you can create in Java.<\/p>\n\n\n\n<ul><li>Non-static nested class (inner class)<\/li><li>Static nested class<\/li><\/ul>\n\n\n\n<p><strong>Recommended reading<\/strong>:<\/p>\n\n\n\n<ul><li>Java Access Modifiers<\/li><li>Java Static Keyword<\/li><\/ul>\n\n\n\n<p>Let&#8217;s first look at non-static nested classes.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"inner-class\">Non-Static Nested Class (Inner Class)<\/h2>\n\n\n\n<p>A non-static nested class is a class within another class. It has access to members of the enclosing class (outer class). It is commonly known as&nbsp;<code>inner class<\/code>.<\/p>\n\n\n\n<p>Since the&nbsp;<code>inner class<\/code>&nbsp;exists within the outer class, you must instantiate the outer class first, in order to instantiate the inner class.<\/p>\n\n\n\n<p>Here&#8217;s an example of how you can declare inner classes in Java.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 1: Inner class<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class CPU {\n    double price;\n    \/\/ nested class\n    class Processor{\n\n        \/\/ members of nested class\n        double cores;\n        String manufacturer;\n\n        double getCache(){\n            return 4.3;\n        }\n    }\n\n    \/\/ nested protected class\n    protected class RAM{\n\n        \/\/ members of protected nested class\n        double memory;\n        String manufacturer;\n\n        double getClockSpeed(){\n            return 5.5;\n        }\n    }\n}\n\npublic class Main {\n    public static void main(String&#91;] args) {\n\n        \/\/ create object of Outer class CPU\n        CPU cpu = new CPU();\n\n       \/\/ create an object of inner class Processor using outer class\n        CPU.Processor processor = cpu.new Processor();\n\n        \/\/ create an object of inner class RAM using outer class CPU\n        CPU.RAM ram = cpu.new RAM();\n        System.out.println(\"Processor Cache = \" + processor.getCache());\n        System.out.println(\"Ram Clock speed = \" + ram.getClockSpeed());\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Processor Cache = 4.3\nRam Clock speed = 5.5<\/samp><\/code><\/pre>\n\n\n\n<p>In the above program, there are two nested classes:&nbsp;<var>Processor<\/var>&nbsp;and&nbsp;<var>RAM<\/var>&nbsp;inside the outer class:&nbsp;<var>CPU<\/var>. We can declare the inner class as protected. Hence, we have declared the RAM class as protected.<\/p>\n\n\n\n<p>Inside the Main class,<\/p>\n\n\n\n<ul><li>we first created an instance of an outer class&nbsp;<var>CPU<\/var>&nbsp;named&nbsp;<var>cpu<\/var>.<\/li><li>Using the instance of the outer class, we then created objects of inner classes:<br>&nbsp;<code>CPU.Processor processor = cpu.new Processor; CPU.RAM ram = cpu.new RAM();<\/code><\/li><\/ul>\n\n\n\n<p><strong>Note<\/strong>: We use the dot (<code>.<\/code>) operator to create an instance of the inner class using the outer class.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"accessing-members-outer-inner-class\">Accessing Members of Outer Class within Inner Class<\/h3>\n\n\n\n<p>We can access the members of the outer class by using this keyword. If you want to learn about this keyword, visit\u00a0Java this keyword.\u00a0<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 2: Accessing Members<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Car {\n    String carName;\n    String carType;\n\n    \/\/ assign values using constructor\n    public Car(String name, String type) {\n        this.carName = name;\n        this.carType = type;\n    }\n\n    \/\/ private method\n    private String getCarName() {\n        return this.carName;\n    }\n\n\/\/ inner class\n    class Engine {\n        String engineType;\n        void setEngine() {\n\n           \/\/ Accessing the carType property of Car\n            if(Car.this.carType.equals(\"4WD\")){\n\n                \/\/ Invoking method getCarName() of Car\n                if(Car.this.getCarName().equals(\"Crysler\")) {\n                    this.engineType = \"Smaller\";\n                } else {\n                    this.engineType = \"Bigger\";\n                }\n\n            }else{\n                this.engineType = \"Bigger\";\n            }\n        }\n        String getEngineType(){\n            return this.engineType;\n        }\n    }\n}\n\npublic class Main {\n    public static void main(String&#91;] args) {\n\n\/\/ create an object of the outer class Car\n        Car car1 = new Car(\"Mazda\", \"8WD\");\n\n        \/\/ create an object of inner class using the outer class\n        Car.Engine engine = car1.new Engine();\n        engine.setEngine();\n        System.out.println(\"Engine Type for 8WD= \" + engine.getEngineType());\n\n        Car car2 = new Car(\"Crysler\", \"4WD\");\n        Car.Engine c2engine = car2.new Engine();\n        c2engine.setEngine();\n        System.out.println(\"Engine Type for 4WD = \" + c2engine.getEngineType());\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Engine Type for 8WD= Bigger\nEngine Type for 4WD = Smaller<\/samp><\/code><\/pre>\n\n\n\n<p>In the above program, we have the inner class named&nbsp;<var>Engine<\/var>&nbsp;inside the outer class&nbsp;<var>Car<\/var>. Here, notice the line,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if(Car.this.carType.equals(\"4WD\")) {...}<\/code><\/pre>\n\n\n\n<p>We are using&nbsp;<code>this<\/code>&nbsp;keyword to access the&nbsp;<var>carType<\/var>&nbsp;variable of the outer class. You may have noticed that instead of using&nbsp;<code>this.carType<\/code>&nbsp;we have used&nbsp;<code>Car.this.carType<\/code>.<\/p>\n\n\n\n<p>It is because if we had not mentioned the name of the outer class&nbsp;<var>Car<\/var>, then&nbsp;<code>this<\/code>&nbsp;keyword will represent the member inside the inner class.<\/p>\n\n\n\n<p>Similarly, we are also accessing the method of the outer class from the inner class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if (Car.this.getCarName().equals(\"Crysler\") {...}<\/code><\/pre>\n\n\n\n<p>It is important to note that, although the&nbsp;<code>getCarName()<\/code>&nbsp;is a&nbsp;<code>private<\/code>&nbsp;method, we are able to access it from the inner class.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"static-inner-class\">Static Nested Class<\/h2>\n\n\n\n<p>In Java, we can also define a&nbsp;<code>static<\/code>&nbsp;class inside another class. Such class is known as&nbsp;<code>static nested class<\/code>. Static nested classes are not called static inner classes.<\/p>\n\n\n\n<p>Unlike inner class, a static nested class cannot access the member variables of the outer class. It is&nbsp;because&nbsp;the&nbsp;<strong>static nested class<\/strong>&nbsp;doesn&#8217;t require you to create an instance of the outer class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>OuterClass.NestedClass obj = new OuterClass.NestedClass();<\/code><\/pre>\n\n\n\n<p>Here, we are creating an object of the&nbsp;<strong>static nested class<\/strong>&nbsp;by simply using the class name of the outer class. Hence, the outer class cannot be referenced using&nbsp;<code>OuterClass.this<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 3: Static Inner Class<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class MotherBoard {\n\n   \/\/ static nested class\n   static class USB{\n       int usb2 = 2;\n       int usb3 = 1;\n       int getTotalPorts(){\n           return usb2 + usb3;\n       }\n   }\n\n}\npublic class Main {\n   public static void main(String&#91;] args) {\n\n       \/\/ create an object of the static nested class\n       \/\/ using the name of the outer class\n       MotherBoard.USB usb = new MotherBoard.USB();\n       System.out.println(\"Total Ports = \" + usb.getTotalPorts());\n   }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Total Ports = 3<\/samp><\/code><\/pre>\n\n\n\n<p>In the above program, we have created a static class named&nbsp;<var>USB<\/var>&nbsp;inside the class&nbsp;<var>MotherBoard<\/var>. Notice the line,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>MotherBoard.USB usb = new MotherBoard.USB();<\/code><\/pre>\n\n\n\n<p>Here, we are creating an object of&nbsp;<var>USB<\/var>&nbsp;using the name of the outer class.<\/p>\n\n\n\n<p>Now, let&#8217;s see what would happen if you try to access the members of the outer class:<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Example 4: Accessing members of Outer class inside Static Inner Class<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class MotherBoard {\n   String model;\n   public MotherBoard(String model) {\n       this.model = model;\n   }\n\n   \/\/ static nested class\n   static class USB{\n       int usb2 = 2;\n       int usb3 = 1;\n       int getTotalPorts(){\n           \/\/ accessing the variable model of the outer classs\n           if(MotherBoard.this.model.equals(\"MSI\")) {\n               return 4;\n           }\n           else {\n               return usb2 + usb3;\n           }\n       }\n   }\n}\npublic class Main {\n   public static void main(String&#91;] args) {\n\n       \/\/ create an object of the static nested class\n       MotherBoard.USB usb = new MotherBoard.USB();\n       System.out.println(\"Total Ports = \" + usb.getTotalPorts());\n   }\n}<\/code><\/pre>\n\n\n\n<p>When we try to run the program, we will get an error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>error:<\/samp>\n<samp> non-static variable this cannot be referenced from a static context<\/samp><\/code><\/pre>\n\n\n\n<p>This is because we are not using the object of the outer class to create an object of the inner class. Hence, there is no reference to the outer class&nbsp;<code>Motherboard<\/code>&nbsp;stored in&nbsp;<code>Motherboard.this<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"key-points\">Key Points to Remember<\/h3>\n\n\n\n<ul><li>Java treats the inner class as a regular member of a class. They are just like methods and variables declared inside a class.<\/li><li>Since inner classes are members of the outer class, you can apply any access modifiers like\u00a0<code>private<\/code>,\u00a0<code>protected<\/code>\u00a0to your inner class which is not possible in normal classes.<\/li><li>Since the nested class is a member of its enclosing outer class, you can use the dot (<code>.<\/code>) notation to access the nested class and its members.<\/li><li>Using the nested class will make your code more readable and provide better encapsulation.<\/li><li>Non-static nested classes (inner classes) have access to other members of the outer\/enclosing class, even if they are declared private.<\/li><\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn about the nested class in Java and its types with the help of examples. In Java, you can define a class within another class. Such class is known as&nbsp;nested class. For example, There are two types of nested classes you can create in Java. Non-static nested class (inner class) [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[556],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1216"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1216"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1216\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}