A detailed explanation of Java encapsulation __java

Source: Internet
Author: User
Tags modifier

Our daily use of computer mainframe, the CPU, memory, motherboard and so on are packaged into the chassis inside. If there is no chassis, what is the problem, the host, the motherboard are scattered in one place, and then the boot does not boot button, then we need to directly operate the jumper to open the computer. If the operation is careless, it will damage the machine, Then if the case is packaged, then it is not necessary to do so. Embodies the---security characteristics of encapsulation.

You take the computer to add memory, you can directly to the computer to repair the person, and so he added memory after. What you got was the case, and what happened inside you didn't know. The second benefit of encapsulation- isolate the change.

A boot button is provided inside the chassis without the need for you to use the jumper directly to boot, which embodies the encapsulated-easy-to-use feature.

As long as the chassis provides a boot function, you can use the boot function regardless of where the chassis is taken. Embodies the encapsulation of the--- provide repeatability characteristics. Compare without package and have encapsulation ~

One, no encapsulation of the time:

Simulation problems

1. Describe the employee class. Define name, work number, gender of member variables, and working methods. Members use public adornments.

2. Create the Employee object, the object, the method of the member to assign the value. The last object invokes the working method.

3. Summary: If the encapsulation is not used, it is easy to assign a value error, and anyone can change, causing information insecurity.

4. Problem solving: Using encapsulation

public class Employeedemo {public
	static void Main (string[] args) {
		//Create object
		Employee Jack = new Employee (); 
  //invokes a member in the form of a class name, member. Initialize instance variable
		jack.name = "Jack";
		Jack.id = "123456";
		Jack.gender = "male";

		Invoke member Method
		jack.work ();
		System.out.println ();

		Incoming illegal parameter
		Jack.gender = "Not a man";
		Jack.work ();

	}

Class Employee {
	String name;
	String ID;
	String gender;

	public void work () {
		System.out.println (id + ": + name +": "+ gender +" hard work ...) ");
	}
}
Second, there are encapsulation of the time:

1: Set the property of the class to private (the keyword), you cannot use the object name. property name to directly access the object's properties.

public class Employeedemo {public
	static void Main (string[] args) {
		//Create object
		Employee Jack = new Employee (); 
  //Compile error
		Jack.name = "Jack";
		Jack.id = "123456";
		Jack.gender = "male";

		

		Compile an error
		Jack.gender = "Not a man";
		Jack.work ();

	}

Class Employee {
   //use private to decorate the member variable
	private String name;
	Private String ID;
	private String gender;

	public void work () {
		System.out.println (id + ": + name +": "+ gender +" hard work ...) ");
	}
}

2: Modify the employee sex modifier to private

1: compilation does not pass

2:private decorated members can be used in their own class and cannot be used outside of the class.

The gender modifier for the 3:employee class is modified to private and cannot be called outside of the class, so how to set the value for the gender.

1: Externally provided public method for setting object properties

1: Setting set

2: Getting get

2: Add logical judgments to the Set method to filter out illegal data.

3: All the member variable package plus private, to provide a get, set method

public class Employeedemo {public static void main (string[] args) {//create object Employee jack = new Em

		Ployee ();
		Invokes a public method to assign a value to a member variable.
		Jack.setid ("007");
		Jack.setname ("Jack");

		Jack.setgender ("Men xx");
		Gets the value of the instance variable System.out.println (Jack.getgender ());
		System.out.println (Jack.getid ());

		System.out.println (Jack.getname ());

	Invoke member Method Jack.work ();
	Class Employee {private String name;
	Private String ID;

	Private String gender;
	Provides a publicly available get Set method public String GetName () {return name;
	public void SetName (String n) {name = N;
	Public String GetId () {return id;
	} public void SetId (String i) {id = i;
	Public String Getgender () {return gender; public void Setgender (String gen) {if (male). Equals (gen) | |
		"Female". Equals (gen)) {gender = Gen;
		else {System.out.println ("Please enter \" \ "" or "female \"); } public void Work () {System.out.println (id + ": + name +": "+ gender +" hard work ...)
	"); }
}
Third, the advantages of encapsulation:

1: Hide the specific implementation of the class

2: Simple operation

3: Improve the security of object data


Write an example of it ~

Describe a calculator class

Class Calculator {//1. View specific Calculator objects extract the common attributes of all calculators public String name = "My calculator I am the master";
	public double num1;
	public double num2;
	public char option; 2.
		View specific Calculator objects extract the common functions of all calculators//2.1 Define the functional functions that accept data public void init (double A, char op, double b) {num1 = A;
		option = OP;
	num2 = b;  }//2.2 Defines the functionality of the calculation public void calculate () {switch (option) {case ' + ': System.out.println (name +):
	             "+ NUM1 +" + "+ num2 +" = "+ (NUM1 + num2));
       Break
	             Case '-': System.out.println (name + ":" + NUM1 + "-" + num2 + "=" + (num1-num2));
       Break
	             Case ' * ': System.out.println (name + ":" + NUM1 + "*" + num2 + "=" + (NUM1 * num2));
	   Break Case '/': {if (num2!= 0) System.out.println (name + ":" + NUM1 + "/" + num2 + "=" + (
				 NUM1/NUM2));
	             else System.out.println ("divisor cannot be 0!");
	             Break
     }  Case '% ': {//1. Deal with the symbolic problem of the result, so that the symbol of the result satisfies the requirement of mathematics//2. Resolve Nan's problem System.out.println (name + ":" + N
	             UM1 + "%" + num2 + "=" + (num1% num2));
	             Break
	   
	   Default:System.out.println ("You are making trouble, I ignore you, angry you ...");
		}} class Demo9 {public static void main (string[] args) {Calculator cal = new Calculator ();
		Cal.init (41, '% ', 0);
		Cal.calculate ();
	System.out.println ("Finished calculation!)"; and again. }
}














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.