• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static keyword  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How come we can use an object that is created from a static class without declaring it static

for example in the equals() method of the Body class we can say this.key.equals() but key is a static class how can we use key in this way,I thought that since Key is from a static class all of its methods are static,yet we can call them from a non static method?

thanks



 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. When static is applied to a class it is not automatically applied to the class' members. When a class is static, that just means that instances of that class aren't associated with an instance of the outer class. Here's an example of an inner class, and a roughly equivalent static nested class:

The two classes are the same, except that Inner can access the fields of the Outer class directly, because Inner is implicitly associated with an instance of Outer. Static nested classes are not implicitly associated with an instance of the outer class.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adam Chalkley wrote:. . .  in the equals() method of the Body class we can say this.key.equals() but key is a static class  . . .
No, key isn't a static class; Key is. The two are different. The reason for making a nested class static is usually because you want to use it outside its enclosing type. There are restrictions on nested classes. For example:-
  • 1: Inner classes don't have static variable fields.
  • 2: A static nested class doesn't have access to instance members of its enclosing tpe.
  • But apart from that, the key becomes an ordinary object, with instance fields and instance methods.

    I can see some other problems in your code, I am afraid.
  • 1: Your hash code method is peculiar. It is usual to multiply by a prime number, not 57, which isn't prime. And multiply by 31; don't add 31.
  • 2: Your equals method in line 91 is incorrect. You are not taking cognisance of the risk of one of the fields being null. (The hash code method has the same problem.) You are also performing a cast without checking whether the cast will complete normally. Both those things can produce exceptions and equals mustn't throw any exceptions. Lines 99‑101 are simply confusing, and can be simplified no end.
  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!