💻Step 11:Nested Classes – 7th hour + code

 

 

💡Definition

-class inside another class is called as nested class.

nested_classes

💡1- static nested class

It’s is static class which is defined inside another class.

sttclas
  • 💡static nested class can’t access instance variable directly

    sttclass

    💡2- non static class(Inner classes)

    💡2.1- member class

  • It’s is class which is defined inside another class.

    mmbrclas

  • 💡member class can access instance variable directly.

    mmbrclass

    💡2.2- Local class

  • 💡It’s is class which is defined and used inside the method another class.

    localmmbrclass

    💡2.3- Anonymous class

  • 💡It’s is nameless class which is defined inside body of constructor call.

    anoymous

code samples are here
1-Program to create static nested class ‘SmallStatic’ inside Outer class StaticInner and then create object of static nested class ‘SmallStatic’.

package innerClasses;

public class StaticInner { 
static class SmallStatic{ 
SmallStatic(){
System.out.println("i am from static class");
}
} 
public static void main(String[] args) { 
StaticInner.SmallStatic static1=new StaticInner.SmallStatic(); 
} 
}

Run this Program ▶️

2- Program to create member class ‘SmallMember’ inside Outer class MemberOut and then create objec of member class ‘SmallMember’.
package innerClasses;
public class MemberOut { 
class SmallMember{ 
SmallMember(){
System.out.println("i am called");
}
} 
public static void main(String[] args) { 
MemberOut.SmallMember member=new MemberOut().new SmallMember(); 
} 
}
 
 
3-  Program to create Local class ‘SmMth’and create its object inside method ‘shw2’ of Outer class MethodLocOut.
package innerClasses;

public class MethodLocOut { 
void shw2(){ 
class SmMth{ 
SmMth(){
System.out.println("i am called"); 
}
} 
SmMth mth=new SmMth();
} 
public static void main(String[] args) { 
MethodLocOut mLI=new MethodLocOut(); 
mLI.shw2(); 
}
}
 
 4-  Program to create Anonymous class with constructor of Outer class AnonCls.
package innerClasses;

public class AnonCls {
void show(){
System.out.println("hiui");
}

public static void main(String[] args) {
AnonymousClss clss=new AnonymousClss(){
void show(){
System.out.println("hiii");
}
};
clss.show();
}
}
 

Interview Questions —

  • Is nested and inner classes are same?
  • What is difference between non-static and static class?
  • What is difference between instance, local and anonymous class?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.