Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static classes and final classes in java [duplicate]

Tags:

java

android

In Java (and in Android), what's the use of static class and final class declarations?

My question is not about static instances but class declarations like,

static class StaticClass {
    //variables and methods
}

and

final class FinalClass {
    //variables and methods
}

Thanks,

like image 714
gnuanu Avatar asked Dec 03 '22 21:12

gnuanu


2 Answers

Static Nested Classes

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject =
     new OuterClass.StaticNestedClass();

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Final Classes

A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.

http://docs.oracle.com/javase/tutorial/java/IandI/final.html

like image 116
Jabir Avatar answered Dec 10 '22 13:12

Jabir


final classes will restrict for further extends (Inherit).

You can not use static keyword on outer class,static is permitted only to inner classes Static classes

like image 22
Siva Avatar answered Dec 10 '22 12:12

Siva