Three major features of Java-Summary of encapsulation knowledge and summary of three major java packages

Source: Internet
Author: User

Three major features of Java-Summary of encapsulation knowledge and summary of three major java packages

Recently, a friend said that he wanted to say that he was learning java recently. He still had some incomprehension about the object-oriented programming language to help him "transform" faster ", I wrote this article. Because from the perspective of superstructure. All the ideas of object-oriented programming languages are similar, and these three features are the pillars of the ideas. Next I will focus on the three major java features.

The object-oriented programming language has three main features: "encapsulation", "inheritance", and "polymorphism ".

Encapsulation

In object-oriented programming, encapsulation (encapsulation) literally refers to packaging. It refers to encapsulating data and data-based operations by using abstract data types, make it an inseparable independent entity. In fact, it is to encapsulate the methods and data required for object operation in the program to publish its interface. The data is protected inside the abstract data type and the internal details are hidden as much as possible, only some external interfaces are retained so that they are in contact with the external interface. That is to say, the user does not need to know the internal details of the object (of course, they do not know), but can access the object through the interface provided by the object, the common point is that other objects attached to these interfaces can use this object without the need to care about the object implementation methods. This concept is "Don't tell me how you do it, just do it".

Therefore, encapsulation privatize the attributes of an object and provides some methods for attributes that can be accessed by the outside world. If we do not want to be accessed by the outside world, we do not need to provide methods for the outside world. However, if a class is not provided for external access, it makes no sense.

For example, we regard an object as a house with beautiful wallpapers, such as sofas, TVs, and air conditioners, which are private properties of the House. However, if there is no wall block, isn't there any privacy! It is because of the blocked wall that we can both have our own privacy and we can freely change the decoration in it without affecting others. But if there are no doors and windows, what is the significance of a wrapped black box? So other people can see the scenery through the doors and windows. Therefore, doors and windows are the interface for external access from House objects.

Generally, you need to add a private modifier before the attribute in the class. Define the getter and setter methods. Then, the objects in our main function can no longer directly call properties, but can only be called through the getter and setter methods.

Three Advantages of encapsulation

1. Good encapsulation can reduce coupling.

2. The internal structure of the class can be freely modified.

3. More precise member control.

4. Hide information and implement details.

Modifier

First, you need to know what a modifier is. An access modifier can be used to modify the access range of attributes and methods.

In the object-oriented process, we add permissions to encapsulated classes through permission control to restrict the class operation of outsiders, so as to ensure the security of data and methods in the class. A class is a logical entity that encapsulates relevant attributes and methods. For some attributes or methods in an object, they can be private and cannot be accessed by the outside world. It can also be shared and accessible to anyone outside the world. In this way, the object provides different levels of protection for internal data to prevent unexpected changes or incorrect use of the private part of the object in unrelated parts of the program, in this way, the program may encounter unexpected errors.

The modifiers in java 4 are public, protectd, default, and private. This demonstrates the encapsulation of object-oriented systems. We should minimize permissions to improve security.

, Represents the access range of different access modifiers, such as private modified attributes or methods, can only be accessed or used in this class. If no modifier is added, the default value is default. By default, it can be accessed and used in the current class and under the same package.

Access permission package subclass other packages

Public writable

Protect limit ×

Default timeout limit ××

Private region ×××

If no modifier is added before the attribute, the default permission is the default permission. By creating an object, we can directly modify the attribute value without reflecting the encapsulated features. This is not safe in programming, so we need to use encapsulation to improve our code.

Modifier example

First, we define four classes: Person, Parent, Teacher, and Student, respectively, to compare the differences between other packages, subclasses, packages, and classes. The Location Map of each class is shown.

 

Package com. java. test; public class Person {public String name = "Zhang San"; public void introduceMyself () {System. out. println (name );}}

The name is public. If no error is reported during compilation, the public variable has the permission to access this class.

package com.java.test;public class Student { Person p = new Person(); public void test(){  System.out.println(p.uname); }}

Student and Person are in the same package. If no error is reported during compilation, the variable has the same access permission in the package.

package com.java.test1;import com.java.test.Person;public class Teacher extends Person { public int age; Person p = new Person(); public void test1(){  System.out.println(p.uname); }}

Student and Person are not in the same package, but Teacher inherits the Person class. If no error is reported during compilation, the variable has the access permission in the sub-package.

package com.java.test1;import com.java.test.Person;public class Parents { public String uname = "haha"; Person p = new Person(); public void test2(){  System.out.println(p.uname); }}

Parent and Person are not in the same package. If no error is reported during compilation, it means that the variable has the white outer access permission.

After the above tests, if all the compilation is successful, it means that the classes modified with public can access each other in the current class, the same package, the subclass, and other packages.

Similarly, we started to test the protected permission. If Person, Teacher, and Student can be compiled, it means that the classes modified with protected can access each other in the same class, package, and subclass, if Parent compilation fails, it means that protected cannot access each other in classes without any inheritance relationships outside the package.

Similarly, we started to test the default permission. If the Person and Student can be compiled, it means that the classes modified by default can access each other in the class, the same package, and the subclass, and Parent, if the Teacher compilation fails, it means that the default modified class cannot be accessed from each other no matter whether there is any inheritance relationship outside the package.

Similarly, the test of private permission is started. If the Person can be compiled, it means that the classes modified with private can access each other in the class, the same package, and the subclass, while Parent, Teacher, student: classes not modified by private can only be accessed in this class.

Generally, you need to add a private modifier before the attribute in the class. Define the getter and setter methods. Then, the objects in our main function can no longer directly call properties, but can only be called through the getter and setter methods.

Package

Let me explain the role of the package.

Sometimes the program class names may be repeated, so we can use the Package concept to solve our problem. The role of a package is to manage Java files and resolve conflicts with files of the same name. This is similar to the wardrobe. Whether there are different partitions and drawers in the wardrobe, we put the clothes in different categories, more favorable and conducive to our management.

Define a package. We use the package keyword and add our package name.

Package com. java. test; // note: the package name must be placed in the first line of the source program. The package name can be separated by the "." character.

Common Java System packages

Java. (function ). (class) java. lang. (class) contains the java language-based class java. util. (class) contains various tool classes in the language java. io. (class) Class Related to input and output

To use classes in another file in different packages, you need to use the import keyword. For example, import com. java. test1.test. java. If import com. java. test1 * is used, all the files under the package are imported.

This keyword

I. The this keyword mainly has three applications:

(1) this calls the attributes in this class, that is, the member variables in the class;

(2) this calls other methods in this class;

(3) this calls other constructor methods in this class, which must be placed in the first line of the constructor.

Public Class Student {public Student (String name) {// defines a constructor with a form parameter} public Student () {// defines a method, the name is the same as the class, so it is the constructor this ("Hello! "); } String name; // define a member variable name private void SetName (String name) {// define a parameter (local variable) name this. name = name; // pass the value of the local variable to the member variable }}

As shown in the above Code, there is a member variable name, and there is a form parameter in the method, the name is also name, and then the value of the form parameter name in the method is passed to the member variable name.

This keyword indicates the member variables or methods in the object. That is to say, if you add the this keyword before a variable, it refers to the member variable or method of the object, rather than the formal parameter or local variable of the member method. Therefore, in the above Code, this. name represents the member variable in the object, also known as the object property, and the name following it is a form parameter of the method, code this. name = name is to pass the value of the form parameter to the member variable.

If a class has multiple constructor methods, which of the following constructor methods is called by this method is the same as the class name? In fact, this is the same as using other methods to reference the constructor. It uses form parameters to call constructor methods. In the preceding example, a parameter is added after the this keyword, indicating that it references a constructor with parameters. If there are three constructor methods, they are without parameters, with one parameter, and with two parameters. The Java compiler determines which constructor to call based on the number of passed parameters. As shown in the preceding example, this keyword can be used not only to reference member variables, but also to reference constructor methods.

Internal class

Inner Class is easy to understand from the outside. An internal Class is to put the definition of a Class inside the definition of another Class. Of course, classes that contain internal classes are called external classes.

Many beginners may ask why define a class in another class?

Some problems that are difficult to solve by Using Interfaces sometimes exist in our program design, in this case, we can use the capabilities provided by internal classes to inherit multiple specific or abstract classes to solve these program design problems. In this case, the interface only solves some problems, while the internal class makes the multi-inheritance solution more complete.

In Think in java, the most attractive reason for using internal classes is that each internal class can inherit one (Interface) implementation independently, therefore, no matter whether the peripheral class has inherited a certain (Interface) implementation, it has no impact on the internal class.

public interface Father {}public interface Mother {}public class Son implements Father, Mother {}public class Daughter implements Father{ class Mother_ implements Mother{ }}

Internal features

1. The internal class can use multiple instances. Each instance has its own status information and is independent of other peripheral object information.

2. In a single peripheral class, multiple internal classes can implement the same interface in different ways or inherit the same class.

3. Creating internal class objects does not depend on creating peripheral class objects.

4. The internal class has no confusing "is-a" relationship. It is an independent entity.

5. The internal class provides better encapsulation. Except for this peripheral class, none of the other classes can be accessed.

Package com. java. test; public class OuterClass {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;} public void display () {System. out. println ("display of OuterClass is called");} public class InnerClass {public InnerClass () {name = "chenssy"; age = 23;} public OuterClass getOuterClass () {return OuterClass. this;} public void display () {System. out. println ("name:" + getName () + "; age:" + getAge () ;}} public static void main (String [] args) {OuterClass outerClass = new OuterClass (); OuterClass. innerClass innerClass = outerClass. new InnerClass (); innerClass. display (); innerClass. getOuterClass (). display () ;}name: chenssy; age: 23

The display of OuterClass is called.

We need to make it clear that an internal class is a concept during compilation. Once the compilation is successful, it will belong to two completely different classes from the peripheral class (of course they are still related ).

We also see how to reference the internal class: to reference the internal class, we need to specify the object type: OuterClasName. InnerClassName. At the same time, if we need to create an internal class object, we must use the external class object to create an internal class through. new: OuterClass. InnerClass innerClass = outerClass. new InnerClass ();.

At the same time, if we need to generate external Class Object references, we can use OuterClassName. this will produce a reference that correctly references the external class.

In Java, internal classes are mainly divided into member Internal classes, partial internal classes, anonymous internal classes, and static internal classes.

Member internal class

The member internal class is also the most common internal class. It is a member of the peripheral class, so it can access all member attributes and methods of the peripheral class without restriction, although it is private, however, to access the member attributes and rules of the internal class, the peripheral class must be accessed through the internal class instance.

Pay attention to two points in the internal class of the member,

The member's internal class cannot contain any static variables and methods;

The internal class of a member is attached to the peripheral class. Therefore, you can create an internal class only when the peripheral class is created first.

Public class OuterClass {private String str; public void outerDisplay () {System. out. println ("outerClass... ");} public class InnerClass {public void innerDisplay () {// use the peripheral property str =" chenssy... "; System. out. println (str); // use the peripheral method outerDisplay () ;}}/* getxxx () is recommended to obtain the internal class of the member, especially when the constructor of this internal class has no parameters */public InnerClass getInnerClass () {return new InnerClass ();} public static void main (String [] args) {OuterClass outer = new OuterClass (); OuterClass. innerClass inner = outer. getInnerClass (); inner. innerDisplay ();}}

It is recommended that you use getxxx () to obtain the internal class of the member, especially when the constructor of the internal class has no parameters.

Partial sentence internal class

Local internal classes are nested in methods and scopes. The usage of this class is mainly for application and solution complicated problems. We want to create a class to assist our solution, at that time, we don't want this class to be public, so we can create a local internal class.

The local internal class is compiled like the member internal class. It can only be used in the method and attribute. If it is not used, the method and attribute will become invalid.

Defined in the method:

public class Parcel5 { public Destionation destionation(String str){  class PDestionation implements Destionation{   private String label;   private PDestionation(String whereTo){    label = whereTo;   }   public String readLabel(){    return label;   }  }  return new PDestionation(str); } public static void main(String[] args) {  Parcel5 parcel5 = new Parcel5();  Destionation d = parcel5.destionation("chenssy"); }}

Defined in scope:

public class Parcel6 { private void internalTracking(boolean b){  if(b){   class TrackingSlip{    private String id;    TrackingSlip(String s) {     id = s;    }    String getSlip(){     return id;    }   }   TrackingSlip ts = new TrackingSlip("chenssy");   String string = ts.getSlip();  } } public void track(){  internalTracking(true); } public static void main(String[] args) {  Parcel6 parcel6 = new Parcel6();  parcel6.track(); }}

Anonymous internal class

Public class OuterClass {public InnerClass getInnerClass (final int num, String str2) {return new InnerClass () {int number = num + 3; public int getNumber () {return number ;}};/* Note: The semicolon cannot save */} public static void main (String [] args) {OuterClass out = new OuterClass (); innerClass inner = out. getInnerClass (2, "chenssy"); System. out. println (inner. getNumber () ;}} interface InnerClass {int getNumber ();}

1. Anonymous internal classes do not have access modifiers.

2. new anonymous internal class, which must exist first. If we comment out the InnerClass interface, a compilation error occurs.

3. Note the parameters of the getInnerClass () method. The first parameter is modified with final, but the second parameter does not. At the same time, we also found that the second form parameter was not used in the anonymous internal class, so when the form parameter of the method needs to be used by the anonymous internal class, the form parameter must be final.

4. There is no constructor for anonymous internal classes. Because it does not even have a name to construct a method.

Static internal class

Static can modify member variables, methods, code blocks, and other internal classes. static internal classes are called static internal classes, but we prefer nested internal classes. The biggest difference between a static internal class and a non-static internal class is that a reference is implicitly stored after the non-static internal class is compiled, and its usage is directed to its peripheral class. But the static internal class does not exist. This means that the creation of the static internal class does not need to depend on the peripheral class, and it cannot use non-static member variables and methods of any peripheral class.

Public class OuterClass {private String sex; public static String name = "chenssy "; /*** static internal class */static class InnerClass1 {/* static internal class members can exist */public static String _ name1 = "chenssy_static "; public void display () {/** the static internal class can only access static member variables and methods of the peripheral class * cannot access non-static member variables and methods of the peripheral class */System. out. println ("OutClass name:" + name );}} /*** non-static internal class */class InnerClass2 {/* The non-static internal class cannot contain static members */public String _ name2 = "chenssy_inner "; /* any member of the peripheral class can be called in non-static internal classes, whether static or non-static */public void display () {System. out. println ("OuterClass name:" + name );}} /*** @ desc peripheral Class Method * @ author chenssy * @ data 2013-10-25 * @ return void */public void display () {/* external class access static internal class: internal class. */System. out. println (InnerClass1. _ name1);/* The static internal class can be directly created without relying on the peripheral class */new InnerClass1 (). display ();/* non-static internal creation depends on the peripheral class */OuterClass. innerClass2 inner2 = new OuterClass (). new InnerClass2 ();/* Members of the non-static internal class must use instances of non-static internal Classes */System. out. println (inner2. _ name2); inner2.display ();} public static void main (String [] args) {OuterClass outer = new OuterClass (); outer. display ();}}

Summary

The above is a summary of the three major Java features-encapsulation knowledge, which I hope to help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.