"Introduction to Programming (Java) 6.3 private Modifier"

Source: Internet
Author: User
Tags in domain

The modifier private provides the highest protection and lowest visibility: The private decorated domain, method, and nested type, which can only be accessed in its definition class.

6.3.1 Private

There will be some procedural restrictions in the various books, such as:

★ Modify all member variables with private (make all Member Variables private.).

★ Modify any helper method with private. (Make any helper methods private).

These heuristic rules are a self-discipline clause. For Java package designers, the package-level private is already a good natural boundary (no need to deliberately follow the above rules), in some cases, such as [5.2.1 node], the package-level private is very reasonable, but the professional programmers will use a variety of programming languages, the rule of the following is the habit should be formed, Many languages do not have a package-level private access level.

1. Access restrictions apply to the class level

Assuming that Privatedemo declares the private I domain, overwrites object.equals (Object), and defines the private method IsEqual (Privatedemo), You can test the following code in the class Privatedemo that defines the private domain and the method:

publicstatic void Test () {

Privatedemo one = new Privatedemo (8);

Privatedemo = new Privatedemo (8);

System.out.println (One.equals ());

Here:System.out.println (One.isequal ());

Here:System.out.println (ONE.I==TWO.I);

}

This code shows that in the definition class, objects can access each other's private members.

If you move the above code to any other class, compile the times wrong.

2. Privatization of member variables

After the member variable is privatized, the member variable can only be accessed by the external access method. For ease of memory, access method names usually have the convention of reading the method name get+ variable name and setting the method name to set+ variable name. Commonly known as getter and setter.

There is a common problem: since the public getter/setter is provided for a private domain, why not declare the domain as public directly? is there a difference between the two? Is it more convenient to use x.i than x Geti ()?

In this case alone-providing the simplest public getter and setter method for the private domain, it is true that the domain can be declared as public directly and x.i than X. Geti () is more intuitive. But:

(1) In order to unify (with various other situations), it is best to adopt the private domain +public getter/setter in the Java program. Some Java development environments can automatically add Getter/setter methods according to the domain declared in the class body.

(2) If you do not provide the private domain setter method, or add some validation code in the setter, for example, the qualification ID must belong to (0,9999), the format of the date must be YYYY-MM-DD, etc., the value of the private domain is highlighted.

In contrast, in the C # language, specifically this provides a thing called attributes/attributes, to c#3.0, can be simplified to: public int id{get; set;}

Semantically, the attribute is Getter/setter, and the compiler automatically provides a private domain such as _id to persist data.

In writing, you can use an int x= id and id = 5, as in the public domain. In a different perspective, even though C # provides syntactic sugars like properties, it still declares the domain (implicitly) as private.

(3) The private domain is not visible anyway, when a class provides the public Getter/setter method, perhaps the class really has a private domain, or there may not be.

Routines 6?3 a virtual domain

Package accessmodifier;

Public abstract class g2{

Protected G2 () {}

public abstract void SetField (int field);

public abstract int GetField ();

}

You can compose a source file with G2. Non-public class

Class Gx extends g2{

private int field;

@Override public void SetField (int field) {This.field = field;

}

@Override public int GetField () {return field;

}

}

another. java file

Package accessmodifier;

public class framework{

public static void Test () {

G2 g2 = Newclass ();

G2.setfield (100);

System.out.println (G2.getfield () + 566);

}

private static G2 Newclass () {return new Gx ();

}

}

This example is similar to routine 6-2. This example demonstrates a design technique (pattern) that may be called a virtual domain pattern. For the user, the API is an abstract class G2, and provides an abstract method setter and getter method to manipulate its internal state (the virtual domain). The subclass of G2 is not visible, the internal state is not in G2 and is declared by a specific subclass.

Note: In this example, there is a private method that does not provide a public static factory, and How to use the Framework and the G2 class outside of the package and leave it behind for resolution.

Exercise 6-18: Discuss the rule "modify all member variables with private". Tip: See "All" to make a question mark first.

Exercise 6-19: Discuss whether the properties/attributes of C # should be introduced in Java.

Exercise 6-20: What is virtual domain mode?

6.3.2 inheritance and hiding of domains

1. Inheritance of domains

[2.1.4 access modifiers and inheritance] once clarified that a subclass inherits all accessible members of its parent class .

For class hierarchies, the focus of the LSP and is_a relationship is on the behavior of the parent-child type, and the domain is reasonably considered private. Domains mainly involve memory allocations of objects. For the sake of unification, and in line with the official document of the Java language Specification , this book finds that the private domain of the parent class is not inherited.

However, this does not change the fact that the child class object created contains a parent class object. From the memory allocation of an object, the subclass object includes both the parent class definition instance variable and the instance variable that it declares itself. This is why the system automatically calls the constructor in a fixed order, starting with the object class, in the order of the inheritance tree, until the constructor of the class specified by the new keyword.

Regardless of whether or not the subclass does not inherit the private variable of the parent class [1], the subclass cannot access the "own" variable, even if the subclass inherits the private variable. The instance variables of the parent class object typically do not provide additional benefits to subclasses.

★ Data down focus.

2. Hiding the domain

Several domains declared in the parent class, regardless of their access rights (or whether they are inherited), whether static or instance, the subclass hides the domain with the same name in the parent class, and whether the data type is the same does not matter.

Assuming Ducks (Duck) and lame ducks (Lameduck) are parent-child classes, the parent class Duck has 4 access-level * 2-form (instance or static) member variables, and the subclass can be hidden in 8 different ways for each domain of the parent class (data type not considered). These 64 combinations are not interesting, here is a famous example: The lame duck problem .

Duck has two legs and two feet. Lameduck has only one leg and one foot, it is a duck, can construct the following inheritance relationship.

static binding Vs. Method dynamic binding for a routine 6?4 domain

Package oo.accessmodifier;

public class duck{

int feet = 2;

public int Legs () {return feet;} Get ()

}

another. java file

Package oo.accessmodifier;

public class Lameduck extends duck{

int feet = 1;

The override here is very special.

@ Override public int legs () {

return feet;

}

public static void Test () {

Duck d = new Duck ();

Lameduck d = new Lameduck ();

Duck d = new Lameduck ();

System.out.println (D.getclass () + "object has" +d.legs () + "leg");

System.out.println (D.getclass () + "object has" +d. Feet + "foot only");

}

}

This routine mainly describes the non-coordination between the static binding of the domain and the dynamic binding of the method.

Test (), (1) Duck d = new Duck (), Output Duck object has 2 legs 2 feet, (2) Lameduck d = new Lameduck (), Output Lameduck object has 1 legs 1 feet. (3) Duck d = new Lameduck () upward styling, Output Lameduck object has 1 legs 2 feet .

This problem occurs because: (1) The polymorphic variable D points to the object of the subclass, and (2) the domain is statically bound. If the domain feet of the declaring class (which is the parent class) is just right to access, D. The feet is 2; (3) The method is dynamic binding. If the subclass overrides legs ()--in fact a getter method, you can name Getfeet (), execute the code of the actual class, and return the feet of the subclass to 1.

The simple way to fix the bug is to privatize the member variables (the parent class). Thus, the statically bound (parent) domain cannot be used in the subclass code, that is, the D.feet in the code causes a compilation error. Thus, if you need to access feet in a subclass, the polymorphic variable d must be shaped downward, with the code ((Lameduck) d). feet. Thus output: The Lameduck object has 1 legs and 1 feet.

The rewrite method of the subclass legs () is strange, and the implementation of the overridden method is completely replicated. Is it interesting to rewrite the full copy? Comment out first. Output: The Lameduck object has 1 feet and 2 legs.

From 1 legs 2 feet, to 2 legs 1 feet; from the awkward ((Lameduck) d). feet and fully copied rewrite, you can see that the design of the example 6-4 is unnatural. The root cause is that the parent-child class has a domain with the same name, even if the feet--domain is private.

Exercise 6-21: More generally, declare the domain name, method getname () in duck, and if the subclass Lameduck also declares a name, guess what it is designed for? What should you pay attention to when writing code?

Exercise 6-22: The lame question reveals what problems exist in object-oriented technology? What is the underlying cause of the lame problem?

Exercise 6-23: Is there polymorphism in domain access?

Exercise 6-24: Discuss whether the subclass inherits the private domain of the parent class.


[1] Philip Heller, the Java 2 Certification Exam Study Guide (4th edition), Electronic Industry publishing House (English edition). The successor faction.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Introduction to Programming (Java) 6.3 private Modifier"

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.