Thursday, 6 June 2019

Class Access Modifiers



Class Access Modifiers


What does it mean to access a class? 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:

1- Create an instance of class B.
2- Extend class B (in other words, become a subclass of class B).
3- Access certain methods and variables within class B, depending on the access control of those methods and variables.


Default Access

    Default access It's the access control you get when you don't type a modifier in the class declaration. Think of default access as package-level access, because a class with default access can be seen only by classes within the same package.

example:

class Beverage { }

Public Access

    A class declaration with the public keyword gives all classes from all packages access to the public class. In other words, all classes in the Java Universe (JU) have access to a public class.

example:

public class Beverage { }


Final Class

    When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will result in a compiler error.

example:

public final class Beverage {}

Abstract Classes

    An abstract class can never be instantiated. It's sole purpose, mission in life, is to be extended (subclassed). If even a single method is abstract, the whole class must be declared abstract. One abstract method spoils the whole bunch. You can, however, put nonabstract methods in an abstract class.

example:

abstract class Car {
private double price;
public abstract void goFast(); // Abstract method
public void getModel(){}; // Non abstract method
}


Strictfp Class

    Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier, floating points used in the methods might behave in a platform-dependent way.

No comments:

Post a Comment