frazman
frazman

Reputation: 33213

Difference between various forms of declarations in java

I am a noob in Java and am someone who is learning Java after python. Anyways, I am having a hard time figuring this out. Suppose I have the class

class Bicycle{
      ....
 }

and

 public class Bicycle{
    ....}

what is the difference. And what about

  public static class Bicycle{
              // if this can be a valid class def in first place
   }

and then, after this.. lets talk about variables.

    class Bicycle{
     int Gear or public int Gear // whats the difference
    }

When to use which one?

Upvotes: 0

Views: 107

Answers (2)

Pavan Kumar
Pavan Kumar

Reputation: 31

Modifiers are Java keywords that provide information to compiler about the nature of the code, data and classes. It is categorized into two types.

  1. Access modifiers: public, protected, private.
  2. Non-access modifiers (final, Abstract, Synchronized, Native, stricfp).

If you don't specify any access modifier before class, it will takes it as a "default" access specifier.

public class A     : //access specification would be public. This class can be access any where.

class A            : //access specification would be default. This class can be used only in the same package. So, default is called as package level specification

we cannot declare a class as static

public static class A{
}

But we can declare inner classes as static

public class A
{    
     static class B{

     }    
}

To get more clarity refer to Access Modifier in java from "SCJP" by kathy sierra

Upvotes: 3

Paul Bellora
Paul Bellora

Reputation: 55213

These keywords (or lack of them) are known as access modifiers - in short they control the accessibility of classes or members.

Classes have the following modifiers:

  • public - accessible anywhere
  • (no modifier) - only accessible in same package

Class members have more possibilities:

  • public - accessible anywhere
  • protected - only accessible in same package or in an extending class
  • (no modifier) - only accessible in same package
  • private - only accessible in same class file*

*Note that nested classes can access their outer class's private members and vice-versa.

More information on access modifiers can be found here. Also see this helpful article for the basics.


Edit: I missed your middle example, with public static class Bicycle - the static here must mean that Bicycle is a nested class. See this page (which I had already linked in my subscript) for an explanation of nested classes, which break down into static classes and non-static, aka inner, classes.

Upvotes: 5

Related Questions