Class Declarations and Modifiers
Java is a package-centric language; the developers assumed that for good organization and name scoping, we would put all our classes into packages.
The following code is a bare-bones class declaration:
This code compiles just fine, but we can also add modifiers before the class declaration. Modifiers fall into two categories:
- Access Modifiers
- Non-access Modifiers
There are three access modifiers: public, protected and private. But there are four access levels: public, protected, default and private. Classes can have only public or default access.
Class Access
When we say code from one class (class A) has access to another class (class B), it means class A can do one of three things:
- Create an instance of class B.
- Extend class B.
- Access certain methods and variables within class B, depending on the access control of those methods and variables.
Default Access
- A class with default access has no modifier preceding it in the declaration!
- A class with default access can be seen only by classes within the same package.
Public Access
- Public access to a class can be provided by just adding public keyword before declaring the class.
- A class with public access can be seen by all classes from all packages.
Now it will compile successfully.
Non-Access Class Modifiers
We can modify a class declaration using the keyword final, abstract, or strictfp. strictfp is a keyword and can be used to modify a class or a method, but never a variable.
Final Classes
- When used in a class declaration, the final keyword means the class can't be subclassed.
- We should make a final class only if we need an absolute guarantee that none of the methods in that class will ever be overridden.
- The java.lang.String is an example of final class.
Abstract Classes
- An abstract class can never be instantiated.
- An abstract method in a class means the whole class must be abstract.
- An abstract class can have both abstract and non-abstract methods.
- The first concrete class to extend an abstract class must implement all of its abstract methods.
The preceding code will compile fine. However, if we try to instantiate a Car in another body of code, we'll get a compiler error.
Comments
Post a Comment