I was searching in google for something and I got a code like
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
It's a nested class but wondering how it could be accessible ?
It must be a nested class: the static keyword on the class (not methods within it) is only used (and syntactically valid) for nested classes. Such static member classes (to use Java in a Nutshell's common nomenculture) hold no reference to the enclosing class, and thus can only access static fields and methods within it (unlike non-static ones; see any summary of nested classes in Java (also known as inner classes).
It can be accessible like this:
public class EnclosingClass {
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
EnclosingClass.LocationResult locationResult = ...
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
So you could create a class extending it using extends Mainclass.LocationResult and use it with Mainclass.LocationResult instance = ...
Related
In Java, if a nested class is not declared as static, it cannot be accessed within a static context. This means an instance of the inner class can only be created through an instance of the outer class. For example:
class Prac{
class Inner{}
public static void main(){
Inner myObj = new Prac().new Inner();
}
}
For my Java-adjusted brain, this makes sense. If an inner class isn't static, it would require an instance of the outer class to be instantiated from. In c# however, I can declare Inner non-statically as a nested class and directly instantiate it from a static context in the Main method.
I read that c# nested classes are like c++ and not java, but I'm not familiar with how inner classes work in any other way. What are the mechanics underlying nested classes in c#?
Consider that Microsoft strongly suggests to avoid public nested classes.
The core idea of a nested class is to completely hide to everyone an implementation detail of an abstraction. Consider that example:
IUserService
public interface IUserService
{
IEnumerable<string> GetAllUsernames();
}
MockUserServiceProvider
public static class MockUserServiceProvider
{
// Public
public static IUserService New() => new MockUserService();
// Nested Private class
private class MockUserService : IUserService
{
public IEnumerable<string> GetAllUsernames()
{
yield return "Bob";
yield return "Mary";
}
}
}
The goal of the Mock provider is to make available to the public an instance of the interface to Mock, it does not make sense to bind the provider to a specific class type, indeed, in theory, that type just shouldn't exist at all. So the best one can do (Without use some I.L. magic as Moq does for example) is to completely hide the class definition with a private nested class, so that no one can access it.
public class InnerTest {
public static void main(String arg[]) {
A.B.print();
}
}
class A {
static class B {
static void print() {
System.out.println("Hello");
}
}
}
How can i call static class B using class name A although class A is not static
This is not related to the class to be static or not, it is related the static keyword in the method.
take a look about How static keyword exactly works in Java? also read this article Java – Static Class, Block, Methods and Variables
One more aspect how to explain this:
class itself is not static or non static it is just a class.
You anyway can use static keyword only with class members. If you would try to declare InnerTest as static you would have an error that might look like this (so assuming it is not static nested class to some other class)
Illegal modifier for the class InnerTest; only public, abstract &
final are permitted
static nested class can be used as in question because it does not require access to any instance member of InnerTest. In other words it can access static members and only those.
If it needs access to non static members then it can not be static and the way to call would be like new InnerTest().new B().
The static keyword is used to modify a member of a class. When a member is modified with static, it can be accessed directly using the enclosing class' name, instead of using an instance of the enclosing class like you would with a non-static member.
The inner class Inner below is a member of the class Outer:
class Outer {
static class Inner {}
}
Therefore, Inner can be accessed like this:
Outer.Inner
Outer don't need to/cannot be modified by static because it is not a member of a class. It is a class existing in the global scope. To access it, you just write its name - Outer. It does not make sense for it to be non-static because it has no enclosing class. If it were non-static, how are you supposed to access it?
To use the correct terminology, class B is not an inner class; it is a static nested class. See https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html for the definitions of the various types of nested class.
The important keyword is the static keyword in front of the definition of class B. It does not matter whether class A is static or not. In fact, it wouldn't make sense to put static in front of class A's definition.
Because class B is declared static, it doesn't keep a reference to an instance of class A.
I was learning about Nested and Inner classes and this led me to think whether it is possible to extend an Inner class to be a Nested class or not. For example.
public class Outer{
public class Inner{
// notice the lack of static keyword
}
}
public class ExtendedOuter extends Outer{
public static class ExtendedInner extends Inner{
// notice the static keyword
}
}
I did try to compile the code above and I couldn't, but the compile time error I received made me believe that there may be a work around. I can however extend a Nested class to be an Inner class.
This is the compile time error I received.
no enclosing instance of type Outer is in scope
An inner class has a reference to the outer class. You cannot remove it in a subclass. This would be like removing a field in a sub-class.
Actually you can extend the inner class. You just have to provide an instance of Outer that the class will be bound to. To do so, you have to explicitly call the super constructor with the instance.
public class Outer {
public class Inner{
// notice the lack of static keyword
}
}
public class ExtendedOuter extends Outer {
private static Outer outer = new ExtendedOuter(); // or any other instance
public static class ExtendedInner extends Inner {
public ExtendedInner() {
outer.super(); // this call is explicitly required
}
}
}
This also works if you have a nested class that extends another nested class from a different enclosing class.
Your question doesn't make sense. An inner class is already a nested class, and so is any other class defined inside another one. Evidently you don't know what these words mean:
nested class: a class declared inside another one
inner class: a nested class that isn't declared 'static'.
Note that 'static nested' and 'inner' are mutually exclusive. Note also that an inner class can extend a static nested class, but not vice versa.
What your code is actually trying to do is extend the inner class as a static class, which is what causes the error. Not because the extending class is nested.
Just looking for a confirmation.
public class Indeed{
public static class Inner implements Runnable{
public void run()
{
System.out.println("Indeed");
}
}
public static void main (String []args)
{
Indeed.Inner inner = new Indeed.Inner();
inner.run();
}
}
As you can see in the code above, I can declare public void run() without declaring it static. I guess it's implicitly done. Isn't it?
One more question related: Why I cannot use the method run as following: Indeed.Inner.run(); it is static after all, there should not be any need of instantiating the inner member at all? ( I know I am wrong as it does not compile if I do that, however I would like to know why).
Thanks in advance.
As you can see in the code above, I can declare public void run() without declaring it static. I guess it's implicitly done. Isn't it?
No.
One more question related: Why I cannot use the method run as following: Indeed.Inner.run();
Becuase it's not static.
static class is only valid for inner classes and you can point to a static class by its enclosing class as Indeed.Inner.
This is different from non-static inner class where you need an instance of the enclosing class to create an instance of the same class. For example:
Indeed.Inner inner = new Indeed().new Inner();
No, run() is an instance method of the static class Inner. A static (inner) class just makes it possible to use an instance of the class without an enclosing parent instance. When you do Indeed.Inner inner = new Indeed.Inner();, you are creating an instance of the static class, and you are invoking it's run() method on this instance.
A static class is just a regular class, in fact more so than a non-static class.
The difference between a static nested class and a top-level class is just access scoping: the static class can access private members of its enclosing class.
Once you get that cleared up, you won't need to ask the question that you are asking here.
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Non-static nested classes (inner classes) have access to other members of the enclosing class
A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class.
Static inner class
public static class Inner implements Runnable
means you can create the instance of them, without having to create the instance of outer class (Indeed)
Indeed.Inner inner = new Indeed.Inner();
Why I cannot use the method run as following: Indeed.Inner.run() ?
the run method is by default not static. To call Indeed.Inner.run() directly, you need to make run() method static too
Why are you not able to declare a class as static in Java?
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
class OuterClass {
public static class StaticNestedClass {
}
public class InnerClass {
}
public InnerClass getAnInnerClass() {
return new InnerClass();
}
//This method doesn't work
public static InnerClass getAnInnerClassStatically() {
return new InnerClass();
}
}
class OtherClass {
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
Sources :
Oracle tutorial on nested classes
On the same topic :
Java: Static vs non static inner class
Java inner class and static nested class
Top level classes are static by default. Inner classes are non-static by default. You can change the default for inner classes by explicitly marking them static. Top level classes, by virtue of being top-level, cannot have non-static semantics because there can be no parent class to refer to. Therefore, there is no way to change the default for top-level classes.
So, I'm coming late to the party, but here's my two cents - philosophically adding to Colin Hebert's answer.
At a high level your question deals with the difference between objects and types. While there are many cars (objects), there is only one Car class (type). Declaring something as static means that you are operating in the "type" space. There is only one. The top-level class keyword already defines a type in the "type" space. As a result "public static class Car" is redundant.
Class with private constructor is static.
Declare your class like this:
public class eOAuth {
private eOAuth(){}
public final static int ECodeOauthInvalidGrant = 0x1;
public final static int ECodeOauthUnknown = 0x10;
public static GetSomeStuff(){}
}
and you can used without initialization:
if (value == eOAuth.ECodeOauthInvalidGrant)
eOAuth.GetSomeStuff();
...
You can create a utility class (which cannot have instances created) by declaring an enum type with no instances. i.e. you are specificly declaring that there are no instances.
public enum MyUtilities {;
public static void myMethod();
}
Sure they can, but only inner nested classes. There, it means that instances of the nested class do not require an enclosing instance of the outer class.
But for top-level classes, the language designers couldn't think of anything useful to do with the keyword, so it's not allowed.
public class Outer {
public static class Inner {}
}
... it can be declared static - as long as it is a member class.
From the JLS:
Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (§8.1.3).
and here:
The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.
A static keyword wouldn't make any sense for a top level class, just because a top level class has no enclosing type.
As explained above, a Class cannot be static unless it's a member of another Class.
If you're looking to design a class "of which there cannot be multiple instances", you may want to look into the "Singleton" design pattern.
Beginner Singleton info here.
Caveat:
If you are thinking of using the
singleton pattern, resist with all
your might. It is one of the easiest
DesignPatterns to understand, probably
the most popular, and definitely the
most abused.
(source: JavaRanch as linked above)
In addition to how Java defines static inner classes, there is another definition of static classes as per the C# world [1]. A static class is one that has only static methods (functions) and it is meant to support procedural programming. Such classes aren't really classes in that the user of the class is only interested in the helper functions and not in creating instances of the class. While static classes are supported in C#, no such direct support exists in Java. You can however use enums to mimic C# static classes in Java so that a user can never create instances of a given class (even using reflection) [2]:
public enum StaticClass2 {
// Empty enum trick to avoid instance creation
; // this semi-colon is important
public static boolean isEmpty(final String s) {
return s == null || s.isEmpty();
}
}
Everything we code in java goes into a class. Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have the same set of copy to all objects.
So, if Java would have allowed the top class to be static whenever you run a program it creates an Object and keeps overriding on to the same Memory Location.
If You are just replacing the object every time you run it whats the point of creating it?
So that is the reason Java got rid of the static for top-Level Class.
There might be more concrete reasons but this made much logical sense to me.
The only classes that can be static are inner classes. The following code works just fine:
public class whatever {
static class innerclass {
}
}
The point of static inner classes is that they don't have a reference to the outer class object.
I think this is possible as easy as drink a glass of coffee!.
Just take a look at this.
We do not use static keyword explicitly while defining class.
public class StaticClass {
static private int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
Is not that a definition of static class?
We just use a function binded to just a class.
Be careful that in this case we can use another class in that nested.
Look at this:
class StaticClass1 {
public static int yum = 4;
static void printHowAreYou() {
System.out.println("How are you?");
}
}
public class StaticClass {
static int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
StaticClass1.printHowAreYou();
System.out.println(StaticClass1.yum);
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
One can look at PlatformUI in Eclipse for a class with static methods and private constructor with itself being final.
public final class <class name>
{
//static constants
//static memebers
}
if the benefit of using a static-class was not to instantiate an object and using a method then just declare the class as public and this method as static.