Access controls (access control) and final, static keywords

Source: Internet
Author: User
Tags instance method modifier modifiers


Access control is annoying, you ' re going to love this artical.


Access modifiers (from less restrictive to more restrictive):

Public , Protected, default (package access), Private

Non-access modifiers (inluding final, abstract and STRICTFP)


1. Class accesses

(1) Default acess

A class with default access has no modifier preceding it in the declaration!

About default access as Package-level access, because a class with default Access can is seen only by classes within th E same package.


(2) Public access

A class declaration with the public keyword gives all classes from all packages access to the public class.


Remenber that's class can use just two of the four access control Levels:default or public!


(3) Other (nonaccess) Class modifiers

You can modify a class declaration using the keyword final,abstract.


(3-1) Final classes

When used in a class declaration, the final keyword means the class can ' t be subclassed. In the other words, no other class can be ever extend (inherit from) a final class. The methods whose class arefinal are default final.


(3-2) Abstract Classes

An abstract class can never be instantiated.

The methods marked abstract end in a semicolon rather than curly.

You can, however, put the nonabstract methods in an abstract class.

It is legal this abstract class has no abstract methods.


2. Declare Class Members

(0) Access modifiers

Whereas a class can use just two to the four access control levels (default or public), members can use all four:

Public, protected, default, private


The default and protected access control types have almost identical behavior to except for one difference Ioned later.


(1) Public members

When "a" or "variable" is declared public, it means all other classes, regardless of the package they belong to, can access the member (assuming the class itself is visible).


(2) Private members

Members marked private can ' t being accessed by code into any class other than the class in which the private member is Dec Lared. A Private member isinvisible to any code outside the member ' s own class.


What about a subclass that tries to inherit a private member of its superclass?

When a is declared private, a subclass can ' t inherit it.

A subclass can ' t, use, or even is about the private members of its superclass. You can, however, declare a matching to the subclass. But regardless of how it looks, it's not aoverriding method!


(3) Protected and Default members

The protected and default access control levels are almost identical, but with one critical difference. A default may is accessed only if the class accessing the belongs to the same package, whereas a protected m Ember can be accessed (through inheritance) by a subclass even if the subclass are in a different.

Take a look at the following two classes:

Package certification;                                                                      
public class Otherclass {
    void Testit () {     //no modifer means method has default access
        System.out.println ("Ot Herclass ");
    }
}

In another source code file for you have the following:

Package somethingelse;                                                                      
Import certification. Otherclass;

Class Accessclass {public
    static void Main (string[] args) {
        otherclass o = new Otherclass ();
        O.testit ();
    }



From the preceding results, you can so accessclass can ' t use the Otherclass method Testit () because Testit () has Def Ault access, and Accessclass is isn't in the same package as Otherclass. So accessclass can ' t, it, the compiler complains.

Default and protected behavior differ only when we talk about subclasses. If the protected keyword is used to define a and any subclass of the class declaring the member can access it Through inheritance. It doesn ' t matter if the superclass and subclass are in different packages, the protected superclass as still Le to the subclass (although visible is only in a very specific way as we'll be a little later).


Now, let ' s Protected Details.


3. Protected Details

What does it mean for a subclass-outside-the-package to have access to a superclass (parent)? It means the subclass inherits the member. I T does not, however, mean the subclass-outside-the-package can access the member using a reference to a instance of T He superclass. In the other words, protected = inheritance.


Protected does not mean this subclass can treat the Protected superclass as though it were public. So if the subclass-outside-the-package gets a reference to the superclass (by, for example, creating an instance of the SU Perclass somewhere in the subclass ' code], the subclass cannot use the dot operator on the superclass reference to access The protected member.


To a subclass-outside-the-package, a protected member might as as-is default (or even private), when the subclass is USI Ng a reference to the superclass. The subclass can protected member only through inheritance.


Package certification;
public class Parent {
    protected int x = 9;    Protected Access

package other;
Import certification. Parent;

Class Child extends Parent {public
    void Testit () {                                                                  
        System.out.println ("x is" + x);    No problem, child inherites x
        Parent P = new parent ();    Can we acess x using the P reference?
        System.out.println ("x in the parent is" + p.x); Compiler error!
    }
}

The compiler is more than happy to show us the problem:



for a subclass outside the package, the protected member can is accessedonly through inheritance.


Can access modifiers be applied to local variables? No!
There is never a case where an access modifier can be applied to a local variable.


4. Nonaccess member Modifiers:final

(1) Final Methods

The final keyword prevents a method of being overridden in a subclass.

The special method constructor can is final !


(2) Final Fields or local Variables

A final variable has kind of types:

1 It can be a Compile-time constant the won ' t ever change.

2 It can be a-value initialized at run time of you don ' t want changed.

It also means that the final variable either assigns a value at the time of the Declaration (at which time it is compiled), or assigns a value before use (at which point the compiler guarantees this). So final does not mean that the value of the variable must be known at runtime.


If they are running at regular times, there are limits to where they are initialized:

Instance final field can only be initialized in a constructor or instance block before it is used, and cannot be initialized in an instance method.

Static final filed can only be initialized in the static block before it is used.


public class Final {
    final int x = 2;    COMPILE-TIME constant
    final int y;        Blank final, It must be initialized before used, and 
                        //The compiler ensures this
    final int z;                                                                            
    static final int A;
    static {
        A = 8;
        System.out.println ("A is initialized to" + a);
    }
    {
        z = 4;
        System.out.println ("Z is initialized to" + Z);
    }
    Final () {
        y = 6;
        System.out.println ("Y is initialized to" + y);
    }
    public void Testfinal () {
        final int h;    It must be initialized before used, and
                        //The compiler ensures this
        h = 6;
        System.out.println ("H is initialized to" + h);
    }
public static void Main (string[] args) {
        new Final (). testfinal ();
    }


Output



(3) Final Arguments

Method arguments are essentially the same as local variables.

Method argument are declared as final, which of course means it can ' t be modified within the method.


5. Nonaccess member Modifiers:static

Things you can mark as static:

Methods
Variables (non-local)
A class nested within another class, but not within a method.
Initialization blocks


Things you can ' t mark as static:

Constructors (makes no sense a constructor is used only to create instances)

Classes (unless they are nested)
Interfaces
Method local Inner classes
Inner class methods and instance variables
Local variables


You must never, ever, ever mark a class as both final and abstract. They have nearly opposite meanings.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.