Recently, a friend said that he wanted to say that he was learning Java recently, and he still did not understand object-oriented programming language, in order to help him faster “transition”, I wrote this article. Because at the superstructure level. All object-oriented programming languages have the same idea, and these three features are the backbone of the idea, and I will focus on the Java three features.
Object-oriented programming language, with three characteristics, respectively: “encapsulation”, “inheritance”, “polymorphic”.
encapsulation
In object-oriented programming, encapsulation literally means packaging, which uses abstract data types to encapsulate data and data-based operations together into an indivisible and independent entity. In fact, it encapsulates the methods and data needed for the object to run in the program’s exposed interface. The data is protected inside the abstract data type, hiding the internal details as much as possible, and only keeping some external interfaces to make it contact with the external. This means that the user does not need to know the internal details of the object (and certainly does not know), but can access the object through the external interface provided by the object, which is commonly referred to as other objects attached to the interface can use the object without caring about the methods implemented by the object. The concept is “Don’t tell me how you do it, just do it”.
So encapsulation privatized the properties of an object, and provided methods that could be accessed by the outside world. If we didn’t want to be accessed by the outside world, we didn’t have to provide methods to the outside world. But if a class has no methods to access from the outside world, then that class is meaningless.
For example, if we regard an object as a house, the beautiful wallpaper inside, such as sofa, TV, air conditioner, etc. are the private properties of the house, but if there is no wall shelter, there is no privacy! Because of the walls, we can have our own privacy and we can change the decoration without affecting the others. But what’s the point of a tightly wrapped black box if there are no doors or Windows? So people can see through the doors and Windows. So doors and Windows are the interfaces that the house objects leave for the outside world to access.
In general, you add a private modifier to an attribute in a class. Then you define getter and setter methods. And then objects in our main function, we can’t call properties directly anymore, we can only call them through getter and setter methods.
Three big benefits of encapsulation
1. Good encapsulation reduces coupling.
2. The internal structure of the class can be modified freely.
3. More precise control over members.
4. Hide information and implement details.
The modifier
You should first understand what modifiers are. Access modifiers can be used to modify the access scope of properties and methods.
In the process of object oriented, we restrict the manipulation of the class by outsiders by adding permission to the encapsulated class through permission control, so as to ensure the security of the data and methods in the class. A class is a logical entity that encapsulates related properties and methods. Some properties or methods in an object can be private and cannot be accessed by outsiders. It can also be common and accessible to anyone outside the company. In this way, objects provide a different level of protection for internal data, preventing unwanted errors in the program from accidental changes or misuse of the private part of the object by unrelated parts of the program.
In Java, 4 modifiers are public, Protectd, default, and private. This illustrates object-oriented encapsulation, so we need to keep permissions as low as possible to improve security.
The figure represents the access scope of different access modifiers, such as private modified properties or methods, that can only be accessed or used in this class. Without any modifiers, the default is default, which can be accessed and used in the current class and in the same package.
Access rights class Package subclass Other packages
Public ∨ ∨
V. To protect v. to protect
Default ∨ × ×
Private ∨ × × ×
If you do not add any modifiers in front of the property, the default permission is default, and you can modify the property value directly by creating an object, without encapsulating the property. None of this is safe in programming, so we need to use encapsulation to improve our code.
Examples of modifiers
First we define four class Person, Parent and the Teacher, Student, other packages were compared, the subclass, bag, this kind of difference. The location diagram for each class is shown.
package com.java.test;
public class Person {
public String name = "Zhang";
public void introduceMyself(){ System.out.println(name); }}Copy the code
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); }}Copy the code
Student and Person are in the same package. If the compile does not report an error, the variable has the same package access rights.
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); }}Copy the code
Student and Person are not in the same package, but Teacher inherits the Person class
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); }}Copy the code
Parent and Person are not in the same package, and if the compiler does not report an error, the variable has external access rights
If all of the above tests are successful, it means that classes with public modifiers can access each other in their own class, in the same package, in subclasses, and in other packages
Also start testing protected permissions. If Person,Teacher, and Student can compile, then protected classes can access each other within the same class, package, and subclass. Parent compilations cannot access each other in classes that have no inheritance relationship outside the package without specifying protected.
If Person,Student can compile, it means that the class with default modifier can access each other in the same class, package, and subclass. Parent,Teacher compiler classes that do not specify the default modifier can be outside the package and classes that have no inheritance relationship can not access each other
We are also testing private permissions. If Person can be compiled, it means that private classes can be accessed within the same class, package, and child classes, while Parent,Teacher, and Student classes can only be accessed within the same class.
In general, you add a private modifier to an attribute in a class. Then you define getter and setter methods. And then objects in our main function, we can’t call properties directly anymore, we can only call them through getter and setter methods.
package
Let me tell you what the bag does
Sometimes the class name of the program may be duplicated, so we can use the package concept to solve our problems. The package is used to manage Java files and resolve file conflicts with the same name. It’s similar to a wardrobe. Does the wardrobe have different partitions and drawers? We put the clothes in different categories, which is more advantageous and conducive to our management.
To define a package, we use the package keyword, plus our package name.
package com.java.test;
Copy the code
// Note: must be placed in the first line of the source program, package name available “. The package naming convention is all lowercase spelling
Packages commonly used in Java systems
Java.lang.(class) contains the basic Java language classes java.util.(class) contains the various utility classes in the language java.io.(class) contains the input and output related classesCopy the code
The import keyword is needed to use a class from another file in a different package. For example, import com.java.test1.test.java, and import com.java.test1* to import all files in the package.
This keyword
This keyword has three main applications:
(1) This calls an attribute of the class, that is, a member variable of the class; (2) This calls other methods in this class; (3) This calls other constructors of this class on the first line of the constructor.
Public Class Student {Public Student(String name) {// define a constructor with formal arguments} PublicStudent() {// Define a method with the same name as the class and therefore 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}}Copy the code
For example, in this code, we have a member variable name, and we have a formal parameter name in the method, and then we pass the value of the formal parameter name to the member variable name.
The this keyword represents a member variable or method in an object. That is, if you prefix a variable with the this keyword, it refers to the member variable or method of the object, not to the formal parameter or local variable of the member method. For this reason, in the above code, this.name represents the member variable of the object, also known as the property of the object, and the name behind it is the formal parameter of the method. The code this.name=name passes the value of the formal parameter to the member variable.
If there are multiple constructors in a class with the same name, which constructor does this call? In fact, this is the same as using any other method reference constructor, which is called with formal parameters. In the example above, the this keyword is followed by an argument, which means that it refers to a constructor with arguments. If you now have three constructors with no arguments, one argument, and two arguments. The Java compiler then determines which constructor to call based on the number of arguments passed. As you can see from the example above, the this keyword can be used to refer not only to member variables, but also to constructors.
The inner class
An Inner Class is easy to understand from the outside. An Inner Class is the definition of one Class inside the definition of another. Correspondingly, of course, classes that contain inner classes are called outer classes.
Many beginners will ask why define one class inside another?
Sometimes there are problems in our programming that are difficult to solve using interfaces, so we can take advantage of the ability provided by inner classes to inherit multiple concrete or abstract classes to solve these programming problems. It is safe to say that interfaces are only part of the solution, while inner classes complete the solution for multiple inheritance.
There’s a quote in Think in Java that says the most interesting thing about using inner classes is that each inner class inherits an implementation independently, so it doesn’t matter if the outer class already inherits an implementation.
public interface Father {
}
public interface Mother {
}
public class Son implements Father, Mother {
}
public class Daughter implements Father{
class Mother_ implements Mother{
}
}Copy the code
Inner class properties
1. An inner class can have multiple instances, each of which has its own state information and is independent of other peripheral object information.
2. Within a single enclosing class, you can have multiple inner classes implement the same interface in different ways, or inherit from the same class.
3. The time at which the inner class object is created does not depend on the creation of the outer class object.
4. An inner class does not have a confusing IS-A relationship; it is a separate entity.
5. The inner class provides better encapsulation and is not accessible to any other class except the enclosing 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("Calling the display of the OuterClass");
}
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(); }}Copy the code
Name: chenssy; Age: 23 Calls the display function of the OuterClassCopy the code
It is important to be clear that an inner class is a compile-time concept, and once compiled, it is a completely different class from the outer class (although they are still related to each other).
We also saw how to refer to the inner class: we need to specify the type of the object reference inner class: OuterClasName. InnerClassName. Outerclass.innerclass InnerClass = outerClass.new InnerClass(); OuterClass = outerClass.new InnerClass(); .
We can also use outerClassname.this if we need to generate a reference to an external class object. This will generate a reference to the external class correctly.
Inner classes in Java are mainly divided into member inner classes, local inner classes, anonymous inner classes, static inner classes.
Member inner class
Member inner class is also the most common inner class, it is a member of the outer class, so it is unlimited access to all member attributes and methods of the outer class, although it is private, but the outer class to access the inner class member attributes and methods need to access through the inner class instance.
There are two things to note in member inner classes,
- There cannot be any static variables and methods in a member inner class;
- The member inner class is attached to the enclosing class, so the inner class can only be created if the enclosing 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 enclosing property STR ="chenssy..."; System.out.println(str); // Use the outer inner method outerDisplay(); }} /* we recommend using getxxx() to get the InnerClass of a member, especially if the InnerClass constructor has no arguments */ public InnerClassgetInnerClass() {returnnew InnerClass(); } public static void main(String[] args) { OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.getInnerClass(); inner.innerDisplay(); }}Copy the code
I recommend using getxxx() to get a member inner class, especially if the inner class’s constructor has no arguments.
Sentence local inner class
Local inner classes, which are nested in methods and scopes, are mainly used to apply and solve complex problems. We want to create a class to assist our solution. At that point, we don’t want the class to be public, so we can create local inner classes.
Local inner classes are compiled just like member inner classes and can only be used in methods and attributes, without which they are invalidated.
Defined in a 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() {returnlabel; }}return new PDestionation(str);
}
public static void main(String[] args) {
Parcel5 parcel5 = new Parcel5();
Destionation d = parcel5.destionation("chenssy"); }}Copy the code
Define 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(); }}Copy the code
Anonymous inner class
public class OuterClass {
public InnerClass getInnerClass(final int num,String str2){
return new InnerClass(){
int number = num + 3;
public int getNumber() {returnnumber; }}; } 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();
}
Copy the code
1. Anonymous inner classes have no access modifiers.
2. New anonymous inner class, which should exist in the first place. If we comment out the InnerClass interface, we get a compilation error.
3. Notice the getInnerClass() parameter. The first parameter is final, but the second parameter is not. We also find that the second parameter is not used in the anonymous inner class, so when the method parameter needs to be used by the anonymous inner class, the parameter must be final.
Anonymous inner classes have no constructors. Because it doesn’t even have a name to construct.
Static inner class
Static modifies member variables, methods, code blocks, and other inner classes. Inner classes that use static modifiers are called static inner classes, but we prefer to call them nested inner classes. The biggest difference between a static inner class and a non-static inner class is that a non-static inner class implicitly holds a reference to its periphery after compilation. But static inner classes do not, which means that static inner class creation does not depend on the enclosing class, and it cannot use any of the non-static member variables and methods of the enclosing class.
public class OuterClass {
private String sex;
public static String name = "chenssy"; InnerClass1{public static String _name1 = / static class innerclass */ static class innerclass {public static String _name1 ="chenssy_static";
public void display(){/* * Static inner classes can only access static member variables and methods of the enclosing class */ system.out.println (){/* * static inner classes can only access static member variables and methods of the enclosing class */ system.out.println (){/* * static inner classes can only access static member variables and methods of the enclosing class */ system.out.println ("OutClass name :"+ name); }} /** * a non-static inner class */ class InnerClass2{/* A non-static inner class cannot have a static member */ public String _name2 ="chenssy_inner"; /* A non-static inner class can call any member of the enclosing class, whether static or non-static */ public voiddisplay(){
System.out.println("OuterClass name:"+ name); }} /** * @desc external class method * @author chenssy * @data 2013-10-25 * @return void
*/
public void display(){/* Innerclass.println (innerclass._name1); */ system.out.println (innerclass._name1); /* Static InnerClass1().display(); /* Static inner classes can create instances directly without relying on outer classes */ new InnerClass1(). Outerclass.innerclass2 () = new OuterClass().new innerclass (); /* Members of the orientation non-static inner class need to use an instance of the non-static inner class */ system.out.println (inner2._name2); inner2.display(); } public static void main(String[] args) { OuterClass outer = new OuterClass(); outer.display(); }}Copy the code