0

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.