ADVERTISEMENT
ADVERTISEMENT

Java program to explain static class

It is possible to make a class static, but the only inner class can be declared as static. An Outer class can not be declared as static.

To make a class static, you have to use a static keyword before class keyword while declaring static class. Static classes are required when you want to create an object of the inner class to access their methods without creating an object of the outer class. With the help of the static inner class, you can directly create an object of the class.

Static Class with Non Static Method:

//Java program to demonstrate example of static class.

import java.util.*;

public class StaticClassExample {
    static int a = 0;

    //static class declaration
    static class ClsInner {
        //method of static class
        public void dispMessage() {
            a = 20;
            System.out.println("Value of a: " + a);
        }
    }

    //main()
    public static void main(String[] s) {
        //create object of static inner class
        StaticClassExample.ClsInner objClsInner = new StaticClassExample.ClsInner();

        objClsInner.dispMessage();
    }
}

Output:

Value of a: 20

Static Class with Static Method:

import java.util.*;

public class StaticClassExample {
    static int a = 0;

    //static class declaration
    static class ClsInner {
        //static method of static class
        public static void dispMessage() {
            a = 20;
            System.out.println("Value of a: " + a);
        }
    }

    //main()
    public static void main(String[] s) {
        //no need to create object
        StaticClassExample.ClsInner.dispMessage();
    }
}

Output:

Value of a: 20

Java Static Variable, Class, Method & Block Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.