Java Access Learning--java access Modifiers

Source: Internet
Author: User
Tags modifier modifiers string format

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels is:

    • Visible to the package. The default. No modifiers is needed.

    • The Visible to the class is only (private).

    • Visible to the World (public).

    • Visible to the package and all subclasses (protected).

Default Access modifier-no Keyword:

Default access modifier means we don't explicitly declare an access modifier for a class, field, method, etc.

A variable or method declared without any access control modifier are available to any other class in the same package. The interface is implicitly public static final and the methods in an interface is by default public.

Example:

Variables and methods can be declared without any modifiers, as in the following examples:

String Version = "1.5.1";

 Boolean ProcessOrder () {
   returntrue;
}
Private Access modifier-private:

Methods, Variables and constructors that is declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that is declared private can is accessed outside the class if public getter methods is present in the class.

The Using the private modifier is the main-from-the-object encapsulates itself and hide data from the outside world.

Example:

The following class uses private access control:

 Public class Logger {
   private  String format;
     Public String GetFormat () {
      returnthis. format;
   }
     Public void setformat (String format) {
      this. format = format;
   }
} 

Here, the format variable of the Logger class are private, so there ' s no-to-other classes to retrieve or set Its value directly.

The variable available to the outside world, we defined and public methods: GetFormat (), which return s the value of format, andSetFormat (String), which sets its value.

Public Access Modifier-public:

A class, method, constructor, interface etc declared public can is accessed from any other class. Therefore fields, methods, blocks declared inside a public class can is accessed from any class belonging to the Java Univ Erse.

However if the public class we were trying to access was in a different package and then the public class still need to be impo RTed.

Because of class inheritance, all public methods and variables of a class is inherited by its subclasses.

Example:

The following function uses public access control:

 Public Static void Main (string[] arguments) {
   //  ...
}

The main () method of an application have to is public. Otherwise, it could not being called by a Java interpreter (such as Java) to run the class.

Protected Access modifier-protected:

Variables, methods and constructors which is declared protected in a superclass can is accessed only by the subclasses in Other package or any class within the "protected members" class.

The protected access modifier cannot is applied to class and interfaces. Methods, fields can is declared protected, however Methods and fields in a interface cannot is declared protected.

Protected Access gives the subclass a chance to use the helper method or variable and while preventing a nonrelated class fro m trying to use it.

Example:

The following parent class uses protected access control, to allow its child class override Openspeaker () method:

 class   Audioplayer { protected  boolean   Openspeaker (Speaker SP) { //  implementation details  }}  class   Streamingaudioplayer { boolean   Openspeaker (Speaker sp) { //  Implementation details   

Here, if we define Openspeaker () method as private and then it would is not being accessible from any other class other th An audioplayer. If we define it as public and then it would become accessible to all of the outside world. But our intension are to expose this method to the its subclass only, thats why we used protected modifier. Access to sub-classes)

Examples in the Netty

Abstract classAbstractnioselectorImplementsNioselector {//NIO Selector
    protected volatileSelector Selector; //Internal Task Queue
    Private FinalQueue<runnable> Taskqueue =NewConcurrentlinkedqueue<runnable>(); //Selector Cycle
     Public voidrun () { for (;;) {
            Try {
                //working with internal task queues
Processtaskqueue (); //Handling Selector Event correspondence Logic
process (selector); } Catch(Throwable t) {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//Ignore.
                }
            }
        }
    }

    Private voidProcesstaskqueue () { for (;;) {
            FinalRunnable task =Taskqueue.poll (); if(Task = =NULL) {
                 Break;
        } task.run (); }
    }

    protected Abstract voidProcess (Selector Selector)throwsIOException; }
Abstract classAbstractnioworkerextendsAbstractnioselectorImplementsWorkerprotected voidProcess (Selector Selector)throwsIOException {Set<SelectionKey> Selectedkeys =Selector.selectedkeys (); if(Selectedkeys.isempty ()) {return; }
         for(Iterator<selectionkey> i =selectedkeys.iterator (); I.hasnext ();) {Selectionkey k=I.next ();
            I.remove (); Try {
                intReadyops =K.readyops (); if((Readyops & selectionkey.op_read)! = 0 | | readyops = = 0) {
                    if(!read (k)) {
                        //Connection already closed-no need to handle write.
                        Continue; }
                }
                if((Readyops & selectionkey.op_write)! = 0) {writefromselectorloop (k); }
            } Catch(Cancelledkeyexception e) {close (k); }

            if(Cleanupcancelledkeys ()) { Break;//Break the loop to avoid concurrentmodificationexception
            }
        }
    }
Access Control and Inheritance:

The following rules for inherited methods is enforced:

    • Methods declared public in a superclass also must is public in all subclasses.

    • Methods declared protected in a superclass must either is protected or public in subclasses; They cannot be private.

    • Methods declared without access control (no modifier was used) can is declared more private in subclasses.

    • Methods declared private is not inherited at all, so there was no rule for them.

Java Access Learning--java access Modifiers

Related Article

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.