Recently, a friend said that he wanted to say that he was learning Java recently. He still didn't understand object-oriented programming languages. In order to help him "transform" faster, I wrote this article. Because from the superstructure level. The ideas of all object-oriented programming languages are similar, and these three characteristics are the pillars in the thinking. Next, I will focus on explaining the three major characteristics of Java.
An object-oriented programming language has three major features: "encapsulation", "inheritance", and "polymorphism".
Package
In object-oriented programming, encapsulation (encapsulation) is literally the meaning of packaging, which means using abstract data types to encapsulate data and data-based operations together, making them an inseparable independent entity. In fact, it is to encapsulate the methods and data required for the object to be run in the program to publish its interface. The data is protected inside the abstract data type, hiding internal details as much as possible, and only retaining some external interfaces to make it contact the outside. In other words, the user does not need to know the details inside the object (of course, there is no way to know it), but the object can be accessed through the interface provided by the object to the outside. In layman's terms, other objects attached to these interfaces do not need to care about the implementation of the object to use this object. The concept is "Don't tell me how you did it, just do it."
Therefore, encapsulation privatizes the properties of an object and provides some methods of attributes that can be accessed by the outside world. If we do not want to be accessed by the outside world, we do not have to provide methods to access by the outside world. But if a class does not provide methods to the outside world to access, then this class has no meaning.
For example, we regard an object as a house, and the beautiful wallpapers inside, such as sofas, TVs, air conditioners, etc., are all private attributes of the house, but if there is no wall covering, then there is no privacy at all! It is because of the blocking wall that we can not only have our own privacy but also change the interior decorations at will without affecting others. But if there are no doors and windows, what is the meaning of a tightly wrapped black box? Therefore, others can also see the scenery inside through doors and windows. Therefore, doors and windows are the interfaces left by the object of the house for the outside world to access.
Generally, the private modifier should be added before the attribute in the class. Then define the getter and setter methods. Then, the objects in our main function can no longer call properties directly, and can only be called through getter and setter methods.
Three benefits of packaging
1. A good package can reduce coupling.
2. The structure inside the class can be freely modified.
3. More precise control of members can be given.
4. Hide information and implement details.
Modifier
First of all, you need to understand what a modifier is. Access modifiers can be used to modify the access scope of attributes and methods.
In the object-oriented process, we use permission control to add permissions to the encapsulated class to restrict outsiders' manipulation of the class, so as to ensure the security of data and methods in the class. It can be said that a class is a logical entity that encapsulates related attributes and methods. For certain properties or methods in an object, they can be private and cannot be accessed by the outside world. It can also be shared and can be accessed by any outsider. In this way, objects provide different levels of protection for internal data to prevent unrelated parts of the program from accidentally changing or using private parts of the object incorrectly, causing unnecessary errors to occur in the program.
The modifiers in java are public, protected, default, and private. This shows the object-oriented encapsulation, and we must try our best to minimize permissions, so as to improve security.
As shown in the figure, it represents the access scope of different access modifiers, such as the properties or methods modified by private, which can only be accessed or used in this class. If no modifier is added, default is default, and it can be accessed and used by default in the current class and the same package.
Access permissions class bun subclass other packages
public ∨ ∨ ∨ ∨
protect ∨ ∨ ∨ ×
default ∨ ∨ × ×
private ∨ × × ×
If no modifier is added before the attribute, the default permission is default. We can directly modify the attribute value by creating an object, and the encapsulation characteristics are not reflected. This is not safe in programming, so we need to use encapsulation to improve our code.
Example of modifiers
First, we define four classes Person, Parent, Teacher, Student, and compare the differences between other packages, subclasses, packages, and this class. The location diagram 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 there is no error in the compilation, it means that the public variable has access to 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 there is no error in compilation, it means that the variable has access rights in the same 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 there is no error in the compilation, it means that the variable has access rights in the subpackage.
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 there is no error in the compilation, it means that the variable has no access permissions.
After the above test, if all of them can be compiled and passed, it means that the classes modified with public can access each other in this class, same package, subclass, and other packages.
We also started to test the protected permission problem. If Person, Teacher, and Student can compile and pass, it means that classes modified with protected can access each other in this class, same package, and subclasses. If Parent does not compile and does not pass, it means that protected cannot access each other in classes without inheritance relationships outside the package.
Also start testing the default permission problem. If Person and Student can compile and pass, it means that classes modified with default can access each other in this class, same package, and subclasses. Parent and Teacher compile without passing the parent and Teacher class can not access each other regardless of whether there is an inheritance relationship.
We also started to test the private permission problem. If Person can be compiled and passed, it means that classes modified with private can access each other in this class, same package, and subclasses. Parent, Teacher, and Student compiled without passing the parent, Teacher, and Student can only access the private class modified with this class.
Generally, private modifiers should be added before the attributes in the class. Then define the getter and setter methods. Then, the objects in our main function can no longer call properties directly, and can only be called through getter and setter methods.
Bag
Let me tell you the function of the bag
Sometimes when you encounter the program's class name may be duplicated, we can use the concept of package to solve our problem. The purpose of the package is to manage Java files and resolve conflicts of files with the same name. This is similar to a wardrobe. Do we have different partitions and drawers in the wardrobe? We place the clothes separately in different categories, which is more conducive to our management.
To define a package, we use the package keyword, plus our package name.
package com.java.test;//Note: It must be placed in the first line of the source program, and the package name can be separated by the "." sign. The naming specification of the package is spelled with all lowercase letters.
Commonly used packages in Java system
java.(Function).(Class) java.lang.(Class) contains the basics of java language java.util.(Class) contains various tool classes in the language java.io.(Class) contains input and output related classes
To use the class in another file in different packages, you need to use the import keyword. For example, import com.java.test1.test.java. At the same time, if import com.java.test1*, import all files under the package.
this keyword
1. There are three main applications of this keyword:
(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 constructors in this class, and should be placed in the first line of the constructor when calling.
Public Class Student { public Student(String name) { //Define a constructor with formal parameters} public Student() { //Define 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 in the above code, there is a member variable name, and there is a formal parameter in the method, and the name is also name. Then the value of the formal parameter name is passed to the member variable name in the method.
The keyword this represents member variables or methods in the object. That is to say, if a variable is added with this keyword, it refers to the member variable or method of the object, rather than the formal parameters or local variables of the member method. For this reason, in the above code, this.name represents the member variable in the object, also known as the object's properties, and the name followed is the formal parameter of the method. The code this.name=name is to pass the value of the formal parameter to the member variable.
If there are multiple constructors in a class because their names are the same and the same as the class name, then which constructor is this called? In fact, this is the same as using other methods to refer to constructors, and they are called through formal parameters. As in the above example, if a parameter is added after this keyword, it means that it refers to a constructor with parameters. If there are now three construction methods, namely, no parameters, one parameter, and two parameters. Then the Java compiler will determine which constructor to call based on the number of passed parameters. As can be seen from the above example, this keyword can be used not only to reference member variables, but also to reference constructors.
Internal class
Inner Class is very easy to understand from the outside. Internal class is to place the definition of one class inside the definition of another class. Of course, corresponding to this, a class containing an inner class is called an outer class.
Many beginners will definitely ask why one class should be defined in another class?
Sometimes there are some problems in our programming that are difficult to solve using interfaces. At this time, we can use the ability provided by internal classes to inherit multiple concrete or abstract classes to solve these programming problems. It can be said that interfaces only solve some problems, while internal classes make the solution of multiple inheritance more complete.
There is a sentence in "Think in Java": The most attractive reason for using inner classes is that each inner class can independently inherit an implementation (interface) independently, so whether the peripheral class has inherited a certain implementation (interface) has no effect on the inner class.
public interface Father {}public interface Mother {}public class Son implements Father, Mother {}public class Daughter implements Father{ class Mother_ implements Mother{ }}Internal class features
1. The internal class can use multiple instances, each instance has its own state information and is independent of other peripheral object information.
2. In a single peripheral class, multiple inner classes can implement the same interface in different ways, or inherit the same class.
3. The moment when creating an internal class object does not depend on the creation of peripheral class objects.
4. There is no confusing "is-a" relationship in the internal class, it is an independent entity.
5. The inner class provides better encapsulation, and other classes cannot be accessed except for the peripheral class.
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("The 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: 23The display of OuterClass is called
We need to be clear that internal classes are a compile-time concept. Once compiled successfully, they belong to two completely different classes from peripheral classes (of course they are still related).
We also see how to reference inner class: Referring to inner class We need to specify the type of this object: OuterClasName.InnerClassName . At the same time, if we need to create an inner class object, we must use the external class object to create an inner class through .new: OuterClass.InnerClass innerClass = outerClass.new InnerClass();.
At the same time, if we need to generate a reference to the external class object, we can use OuterClassName.this, so that we can generate a reference to the external class correctly.
In Java, internal classes are mainly divided into member internal classes, local internal classes, anonymous internal classes, and static internal classes.
Member internal class
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 limitation. Although it is private, if the peripheral class wants to access the member attributes and methods of the internal class, it needs to access through the internal class instance.
Two points should be paid attention to in the internal class of members.
There cannot be any static variables and methods in the internal class of the member;
Member internal classes are attached to peripheral classes, so internal classes can be created only if the peripheral classes are created first.
public class OuterClass { private String str; public void outerDisplay(){ System.out.println("outerClass..."); } public class InnerClass{ public void innerDisplay(){ //Use the attribute str in the peripheral str = "chenssy..."; System.out.println(str); //Use the method outerDisplay(); } } /*Recommended to use getxxx() to get member internal classes, especially when the constructor of the inner 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(); }}I personally recommend using getxxx() to get member internal class, especially when the constructor of this internal class has no parameters.
Sentence local internal class
Local internal classes are nested within methods and scopes. The use of this class is mainly to apply and solve relatively complex problems. I want to create a class to assist our solution. At that time, I don’t want this class to be public, so we can create local internal classes.
Local inner classes are compiled like member inner classes. They can only be used in this method and attribute. If they are not in this method and attribute, they will be invalid.
Defined in the method:
public class Parcel5 { public Destionation destination(String str){ class PDestionation implements Destion{ private String label; private PDestion(String whereTo){ label = whereTo; } public String readLabel(){ return label; } } return new PDestion(str); } public static void main(String[] args) { Parcel5 parcel5 = new Parcel5(); Destion d = parcel5.destionation("chenssy"); }}Defined within 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: semicolons 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, this class must exist first. If we comment out that InnerClass interface, a compilation error will occur.
3. Pay attention to the formal parameters of the getInnerClass() method. The first formal parameter is modified with final, while the second one does not. At the same time, we also found that the second formal parameter has not been used in anonymous inner class, so when the formal parameter of the method needs to be used by anonymous inner class, then this formal parameter must be final.
4. There is no constructor for anonymous internal classes. Because it doesn't even have a name to construct it.
Static inner class
static can modify member variables, methods, code blocks, and other internal classes. We call inner classes modified with static as static, but we prefer to call them nested internal classes. The biggest difference between static inner classes and non-static inner classes is that after compilation is completed, a reference will be hidden, and the use will point to its periphery. But static inner class does not, which means that static inner class creation does not need to rely on peripheral classes, 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 inner class*/ static class InnerClass1{ /* static members can exist in static inner class*/ public static String _name1 = "chenssy_static"; public void display(){ /* * Static inner class can only access static member variables and methods of peripheral class* cannot access non-static member variables and methods of peripheral class*/ System.out.println("OutClass name :" + name); } } /** * Non-static inner class*/ class InnerClass2{ /* Static members cannot exist in non-static inner classes*/ public String _name2 = "chenssy_inner"; /* Any member of the peripheral class can be called in non-static inner 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(){ /* Peripheral class accesses static inner class: inner class. */ System.out.println(InnerClass1._name1); /* A static inner class can be created directly without relying on peripheral classes*/ new InnerClass1().display(); /* A non-static inner creation needs to rely on peripheral classes*/ OuterClass.InnerClass2 inner2 = new OuterClass().new InnerClass2(); /* Members of non-static inner class need to use instances of non-static inner class*/ System.out.println(inner2._name2); inner2.display(); } public static void main(String[] args) { OuterClass outer = new OuterClass(); outer.display(); }}Summarize
The above is the summary of the three major Java features - encapsulated knowledge that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!