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{
}
public static void main(String[] args) {
StaticInner.SmallStatic static1=new StaticInner.SmallStatic();
}
}
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{
}

}
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 mth=new SmMth();
}
public static void main(String[] args) {
MethodLocalInner mLI=new MethodLocalInner();
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();
}
}

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 )

Google photo

You are commenting using your Google 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.