Java access modifiers and the scope of the variables explain _java

Source: Internet
Author: User
Tags class definition control characters inheritance modifier modifiers

Java access modifier (access control character)
Java uses modifiers to control access and other features of classes, properties, and methods, usually at the very front of the statement. For example:

public class ClassName {
  //Body of class
}
private Boolean myflag;
Static final double weeks = 9.5;
protected static final int boxwidth =;
public static void Main (string[] arguments) {
  //body of

Java has many modifiers, divided into access modifiers and non-access modifiers. This section describes the access modifiers only, and the non-access modifiers are described later.

Access modifiers, also called access control characters, are keywords that control the use of classes, member variables, and methods.

In object-oriented programming, access control characters are an important concept that you can use to protect access to classes, variables, methods, and construction methods.

Java supports four different access rights:

Public: Common

Classes, methods, construction methods, and interfaces that are declared public can be accessed by any other class.

If several mutually accessible public classes are distributed in a package that is not in use, you need to import the package that contains the corresponding public class. Because of the inheritance of a class, all public methods and variables of a class can be inherited by its subclasses.

The following methods use public access control:

public static void Main (string[] arguments) {
  //body of

The Java program's main () method must be set to public, otherwise the Java interpreter will not be able to run the class.
Protected: Protected

Variables, methods, and constructs that are declared as protected can be accessed by any other class in the same package, or by subclasses in different packages.

Protected access modifiers cannot modify classes and interfaces, methods and member variables can be declared as protected, but the member variables and member methods of an interface cannot be declared as protected.

Subclasses can access the methods and variables declared by the protected modifier, which protects unrelated classes from using these methods and variables.

The following parent class uses the protected access modifier, and the subclass overloads the Bark () method of the parent class.

public class dog{
  protected void bark () {
    System.out.println ("bark, don't Come over")
  ;
}
Class Teddy extends dog{//Teddy
  void bark () {
    System.out.println ("Bark, I'm so scared, don't follow me");
  }

If the bark () method is declared private, a class other than dog will not be able to access the method. If bark () is declared public, then all classes can access the method. If we just want the method to be visible to subclasses of its class, declare the method as protected.
Private: Personal

Private access modifiers are the strictest level of access, so methods, variables, and constructors that are declared private can only be accessed by the owning class, and classes and interfaces cannot be declared private.

Variables declared as private access types can only be accessed by external classes through the public Getter/setter method in the class.

The use of private access modifiers is used primarily to hide the implementation details of the class and to protect the data of the class.

The following class uses a private access modifier:

public class dog{
  private String name;
  private int age;
  Public String GetName () {return
    name;
  }
  public void SetName (String name) {
    this.name = name;
  }
  public int getage () {return age
    ;
  }
  public void Setage (int age) {
    this.age = age;
  }
}

example, the name, age variable in the dog class is a private variable, so other classes cannot directly get and set the value of the variable. To enable other classes to manipulate the variable, two pairs of public methods are defined, GetName ()/setname () and Getage ()/setage (), which are used to get and set the value of the private variable.

This is a keyword in Java, which is described in this chapter, and you can click on the Java this keyword for a preview.

The way to define access to a private variable in a class is customarily named: precede the variable name with "get" or "set" and capitalize the first letter of the variable. For example, the method to get the private variable name is GetName (), and the method of setting name is SetName (). These methods are often used and have a specific salutation, called Getter and Setter methods.
Default: Do not use any keywords

Properties and methods declared without using any modifiers are visible to classes within the same package. The variables in the interface are implicitly declared as public static final, and the methods in the interface have access by default to public.

As the following example shows, the definition of classes, variables, and methods does not use any modifiers:

Class dog{
  String name;
  int age;
 
  void Bark () {//Barking
    System.out.println ("Barking, don't Come");
  }
  void hungry () {//Hunger
    System.out.println ("host, I am Hungry");
  }

Access control and inheritance

Note that the following methods inherit the rule that readers of the inheritance concept can skip here, or click Java Inheritance and polymorphic previews:
A method declared public in a parent class must also be public in a subclass.
A method declared as protected in a parent class is either declared as protected in a subclass, or declared as public. cannot be declared private.
The default modifier declaration method in a parent class that can be declared private in a subclass.
A method declared private in a parent class cannot be inherited.
How to use Access control characters

Access control characters make it easy for us to control the permissions of the code:
You can declare the access control of a class as public when you need to have the class that you are writing accessed by all other classes.
You can omit access control characters when you need to allow your classes to be accessed only by classes in your own packages.
When you need to control member data in a class, you can set the member data access control character in this class to public, protected, or omit.

Scope of Java variables
In Java, the scope of a variable is divided into four levels: class level, object instance level, method level, block level.

Class-level variables, called global-level variables or static variables, need to be decorated with the static keyword, and you can learn from the static variables in C + +. Class-level variables already exist after class definition, occupy memory space, can be accessed through the class name, and do not need to be instantiated.

Object instance-level variables are member variables that are instantiated before allocating memory space for access.

A method-level variable is a variable that is defined inside a method, which is a local variable.

A block-level variable is a variable that is defined within a block, and the life cycle of the variable is this block, and the block disappears, such as if, for statement blocks. A block is a code that is surrounded by braces, such as:

{
  int age = 3;
  String name = "Www.weixueyuan.net";
  Yes, you can access the age and name variable
  System.out.println (name + "already" + Aged + "old") within the block
;
Error, unable to access the age and name variable
System.out.println (name + "already" + Aged + "old") outside the Block;

Description
Methods can also access variables at the class and instance levels in addition to the variables that can access the method level.
You can access class-level, instance-level variables within a block, and if a block is contained within a method, it also accesses a variable at the method level.
The method-level and block-level variables must be initialized, otherwise they cannot be accessed.

Demo Code:

public class demo{public
static String name = "Micro garden";//class-level variable public
int I//object instance-level variable
//property block, run
when class initializes properties {
Int j = 2;//block-level variable
} public
void Test1 () {
int j = 3;//Method-level variable
if (j = = 3) {
int k = 5;//block-level variable 
   }
//There is no access to block-level variables, block-level variables can only be accessed within blocks
System.out.println ("name=" + name +, i= "+ i +", j= "+ j);
}
public static void Main (string[] args) {
//Do not create object, Access class-level variable
System.out.println (demo.name) directly through class name;

The method to create the object and access it
demo T = new demo ();
T.test1 ();
}

Run Result:

Micro-study Court
Name=, I=0, j=3

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.