group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
263 Members
Join this group to post and comment.
Gaurav Prasad
Gaurav Prasad
Computer Science
19 Jan 2019

Can we declare a class as static?

explain with example?

DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
3mos ago

static is a key word used in Java. It can be applied to a field, a method or an inner class.

A static field, method or class has a single instance for the whole class that defines it, even if there is no instance of this class in the program. If you declare any variable as static,it is known as static variable and if you declare any method as static then it is known as static method.

for example,

class subclass1

{

int a=10;

static int b=20;

static class subclass2

{

static void m1()

{ System.out.println(" it is a static method under static class");

System.out.println("The value of b:"+b);

}

void m2(){

System.out.println(" it is a method under static class");

System.out.println("The value of b:"+b);

}

}

subclass2 obj = new subclass2();

}

class demo{

public static void main(String[] args){

subclass1 obj = new subclass1();

obj1.obj2.m1();

obj1.obj2.m2();

}

}

Shruthi Pillai
Shruthi Pillai
Information Technology
3mos ago

You cannot make a top level class static in Java, the compiler will not allow it, but you can make a nested class static in Java. A top level class is a class which is not inside another class.