"Java from small white to Daniel" The 10th chapter of Object-oriented foundation (bottom)

Source: Internet
Author: User
Tags instance method modifier

"Java from small white to Daniel" paper version has been shelves!!!

Encapsulation and access control

Java Object-oriented encapsulation is achieved through access control of member variables and methods, and access control is divided into 4 levels: private, default, protected, and public, as shown in table 10-1.

Table 101 Access Control for Java class members

? The
can I access control level directlysame class Same Package sub-classes of different packages different packages not subclasses
Private Yes
Default Yes Yes
Protection Yes Yes Yes
Public Yes Yes Yes Yes

These 4 levels of access are explained in more detail below.

Private level {#-0}

Private-level keywords are private, and private-level member variables and methods can be used only within the class in which they reside, and direct access is not allowed in other classes. The private level is the most restrictive. The private level sample code is as follows:

// PrivateClass.java文件package com.a51work6;public class PrivateClass { ①private int x; ②public PrivateClass() { ③x = 100;}private void printX() { ④System.out.println("Value Of x is" + x);}}// HelloWorld.java文件调用PrivateClasspackage com.a51work6;public class HelloWorld {public static void main(String[] args) {PrivateClass p;p = new PrivateClass();//编译错误,PrivateClass中的方法 printX()不可见p.printX(); ⑤}}

The preceding code, ①, declares the Privateclass class, where the code ② line is the declaration of the private instance variable x, and the code ③ line is the construction method that declares the public, and the construction method is described in detail in chapter 12th. The Code section ④ declares a private instance method.

The Code ⑤ Guild in the HelloWorld class has a compile error because the method of Printx () in Privateclass is a private method.

Default Level {#-1}

The default level has no keywords, that is, no access modifiers, and the default level of member variables and methods can be accessed directly within their class and other classes in the same package, but not directly in the classes of different packages.

The default level sample code is as follows:

// DefaultClass.java文件package com.a51work6;public class DefaultClass {int x; ①public DefaultClass() {x = 100;}void printX() { ②System.out.println("Value Of x is" + x);}}

The preceding code, ①, does not have an access restriction modifier before the x variable, and the code for line ② does not have an access restriction modifier. Their access levels have a default access level.

Call the Defaultclass class code in the same package (COM.A51WORK6) as follows:

// com.a51work6包中HelloWorld.java文件package com.a51work6;public class HelloWorld {public static void main(String[] args) {DefaultClass p;p = new DefaultClass();p.printX();}}

The default access level can be accessed in the same package, and the code above can be compiled through.

Calling the Defaultclass class code in a different package is as follows:

// 默认包中HelloWorld.java文件import com.a51work6.DefaultClass;public class HelloWorld {public static void main(String[] args) {DefaultClass p;p = new DefaultClass();// 编译错误,DefaultClass中的方法 printX()不可见p.printX();}}

The Helloworld.java file is not in the same package as the Defaultclass class, Printx () is the default access level, so the P.printx () method cannot be compiled.

Public Level {#-2}

Public-level keywords are publicly, and public-level member variables and methods can be accessed directly in any situation and are the most permissive level of access control.

The public-level sample code is as follows:

// PublicClass.java文件package com.a51work6;public class PublicClass {public int x; ①public PublicClass() {x = 100;}public void printX() { ②System.out.println("Value Of x is" + x);}}

The x variable in line ① of the preceding code is the public level, and the method for line ② is also the public level. Call the Publicclass class code as follows:

// 默认包中HelloWorld.java文件import com.a51work6.PublicClass;public class HelloWorld {public static void main(String[] args) {PublicClass p;p = new PublicClass();p.printX();}}

The Helloworld.java file is not in the same package as the Publicclass class and can be a public printx () method.

Protection level {#-3}

The protection level keyword is protected, and the protection level is exactly the same as the default access level in the same package, but different packets of sub-classes can inherit the protected variables and methods in the parent class, which is known as the protection level, which is the protection of a class's subclasses can inherit the class's variables and methods.

The protection level sample code is as follows:

// ProtectedClass.java文件package com.a51work6;public class ProtectedClass {protected int x; ①public ProtectedClass() {x = 100;}protected void printX() { ②System.out.println("Value Of x is " + x);}}

The x variable in line ① of the above code is the protection level, and the method of line ② is also the protection level.

Call the Protectedclass class code in the same package (COM.A51WORK6) as follows:

// 默认包中HelloWorld.java文件package com.a51work6;import com.a51work6.ProtectedClass;public class HelloWorld {public static void main(String[] args) {ProtectedClass p;p = new ProtectedClass();// 同一包中可以直接访问ProtectedClass中的方法 printX()p.printX();}}

Protected access level in the same package as the default access level, you can directly access the Protectedclass Printx () method, which can be compiled through.

Calling the Protectedclass class code in a different package is as follows:

// 默认包中HelloWorld.java文件import com.a51work6.ProtectedClass;public class HelloWorld {public static void main(String[] args) {ProtectedClass p;p = new ProtectedClass();// 编译错误,不同包中不能直接访问保护方法printX()p.printX();}}

The Helloworld.java file is not in the same package as the Protectedclass class, and the Protection Method Printx () cannot be accessed directly in different packages, so the P.printx () method cannot be compiled.

Inherit the Protectedclass class code in a different package as follows:

// 默认包中SubClass.java文件import com.a51work6.ProtectedClass;public class SubClass extends ProtectedClass {void display() {//printX()方法是从父类继承过来printX(); ①//x实例变量是从父类继承过来System.out.println(x); ②}}

In different packages, subclass inherits the Printx () method and the X instance variable from the Protectedclass class. The code ① line is a method that calls inherited from the parent class, and the code ② line is the instance variable that is called to inherit from the parent class.

There are two ways to access a member: A call that calls its members through a class or object, such as a p.printx () statement, and an inheritance, that is, the subclass inherits the member variables and methods of the parent class.

    • Public access level in any case both ways are possible;
    • The default access level in the same package two access methods can not be accessed outside the package;
    • Protect access levels in the same package as the default access level, both access methods are available. However, the access can only be inherited from different packages;
    • Private access levels can only be accessed by invoking methods in this class and cannot inherit access.

When you are prompted to access a class member, you should try to limit the visibility of the members in the class, with the access level order: private level → default level → protection level → public level, if you are satisfied with the usage.

Static variables and static methods

There is an account (bank accounts) class, assuming it has three member variables: Amount (account amount), interestrate (interest rate), and owner (account name). Of these three member variables, amount and owner are different for different accounts, and the interestrate for all accounts are the same.

The amount and owner variables are related to the account individual, which is called the "instance variable", the interestrate member variable is independent of the individual, or is shared by all account individuals, which is called a "static variable" or "Class variable".

Example code for static and static methods is as follows:

// Account.java文件package com.a51work6;public class Account {// 实例变量账户金额double amount = 0.0; ①// 实例变量账户名String owner; ②// 静态变量利率static double interestRate = 0.0668; ③// 静态方法public static double interestBy(double amt) { ④//静态方法可以访问静态变量和其他静态方法return interestRate * amt; ⑤}// 实例方法public String messageWith(double amt) { ⑥//实例方法可以访问实例变量、实例方法、静态变量和静态方法double interest = Account.interestBy(amt); ⑦StringBuilder sb = new StringBuilder();// 拼接字符串sb.append(owner).append("的利息是").append(interest);// 返回字符串return sb.toString();}}

The static modifier's member variable is statically variable, see Code ③ line. STAITC The method of modification is static method, see code line ④. Conversely, a member variable without a static modifier is an instance variable, as shown in line ① and line ② of code, and no STAITC adornment method is an instance method, see Code ⑥ line.

Note that static methods can access static variables and other static methods, such as accessing interestrate static variables in line ⑤ of code. Instance methods can access instance variables, other instance methods, static variables, and static methods, such as access code ⑦ line Interestby static methods.

Call the account code as follows:

// HelloWorld.java文件package com.a51work6;public class HelloWorld {public static void main(String[] args) {// 访问静态变量System.out.println(Account.interestRate); ①// 访问静态方法System.out.println(Account.interestBy(1000)); ②Account myAccount = new Account();// 访问实例变量myAccount.amount = 1000000; ③myAccount.owner = "Tony"; ④// 访问实例方法System.out.println(myAccount.messageWith(1000)); ⑤// 通过实例访问静态变量System.out.println(myAccount.interestRate); ⑥}}

When a static variable or static method is called, it can be called by the class name or the instance name, the code ① line Account.interestrate calls the static variable through the class name, and the Code ② line Account.interestby (1000) is called by a static method through the class name. The code ⑥ line is a static variable that is called through an instance.

Static code block

The static variable InterestRate described earlier can be initialized at the same time as the Declaration, as shown in the following code.

public class Account {// 静态变量利率static double interestRate = 0.0668;...}

If initializing a static variable is not a simple constant, it needs to be evaluated to initialize, and static (static) blocks of code can be used, which executes at the first time the class is loaded and executes only once. The sample code is as follows:

// Account.java文件package com.a51work6;public class Account {// 实例变量账户金额double amount = 0.0;// 实例变量账户名String owner;// 静态变量利率static double interestRate;// 静态方法public static double interestBy(double amt) {// 静态方法可以访问静态变量和其他静态方法return interestRate * amt;}// 静态代码块static { ①System.out.println("静态代码块被调用...");// 初始化静态变量interestRate = 0.0668; ②}}

The preceding code, ①, is a static block of code that can initialize a static variable in a static code block, as shown in line ② of code, or a static method can be called.

Call the account code as follows:

// HelloWorld.java文件package com.a51work6;public class HelloWorld {public static void main(String[] args) {Account myAccount = new Account(); ①// 访问静态变量System.out.println(Account.interestRate); ②// 访问静态方法System.out.println(Account.interestBy(1000));}}

The account static code block is called when the account class is loaded for the first time. The preceding code, line ①, is the first time the account class is used, and a static code block is called.

Summary of this chapter

This chapter mainly introduces the object-oriented basic knowledge. First, some basic concepts of object-oriented, object-oriented three basic features are introduced. Classes, packages, method overloads, and access control are then described. Finally, static variables, static methods and static code blocks are introduced.

Companion video

Http://edu.51cto.com/topic/1246.html

Supporting source code

Http://www.zhijieketang.com/group/5

and the free version of this book corresponds to a fee version:
    1. Enter Baidu to read ebook

    2. Access to Turing Community ebook

"Java from small white to Daniel" The 10th chapter of Object-oriented foundation (bottom)

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.