Reputation: 33213
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
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.
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
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 anywhereClass members have more possibilities:
public
- accessible anywhereprotected
- only accessible in same package or in an extending classprivate
- 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