Java_ Object oriented programming-2

catalogue primary coverage Learning objectives Section 1 ...
1.1. static variable
1.2. static method
1.3. static code block
2.1. package
2.2. import
2.3. Generate API documents using document comments
3.1. Lead in package
3.2. Permission modifier
3.3. Packaging exercise
4.1. Inheritance and its role
4.2. Method rewriting

catalogue

primary coverage

Learning objectives

Section 1 static keyword

1.1. static variable

1.2. static method

1.3. static code block

Section 2 package and import

2.1. package

2.2. import

2.3. Generate API documents using document comments

Section III encapsulation

3.1. Lead in package

3.2. Permission modifier

3.3. Packaging exercise

Section IV inheritance

4.1. Inheritance and its role

4.2. Method rewriting

primary coverage
  1. static variable
  2. static method
  3. static code block
  4. package and import
  5. Encapsulation
  6. Inheritance
  7. Method rewrite

Learning objectives

Number of sections

Knowledge points

requirement

Section 1 (static keyword)

static variable

understand

static method

understand

static code block

understand

Section 2 (package and import)

Package package

understand

Import import

master

Generating API s using document comments

understand

Section III (encapsulation)

Introduction and function of packaging

master

Permission modifier

master

Section IV (inheritance)

Introduction and function of inheritance

master

Method rewrite

master

Section 1 static keyword

         Static is a keyword in Java. The word itself has a static meaning. Members of a class include variables, methods, constructors, code blocks and internal classes. Static can modify all members except constructors.

         Members decorated with static become static members and belong to a class; Members that do not use static modification become instance members, which belong to each object of the class.

1.1. static variable

         In a class, member variables declared with static are static member variables, also known as class variables. Class variables have the same life cycle as classes and are valid throughout the execution of the application. It has the following characteristics:

  1. It is a public variable of this class, belongs to a class, is shared by all instances of this class, and is explicitly initialized when the class is loaded.
  2. For all objects of this class, there is only one static member variable. Shared by all objects of this class!!
  3. It is generally called with "class name. Class attribute / method". (static members can also be accessed through object references or class names (no instantiation is required.)
  4. Non static members cannot be accessed directly in static methods.

[example 1] static variable

public class Student { //Member variable private int sno;//Student number private String name;//full name private String sex;//Gender private double score;//fraction private String cup;//glass //private static String waterDispenser;// Water dispenser private static String classRoom;//Classroom number //private static String teachName;// Instructor's name //Construction method public Student(){ } public Student(int sno, String name, String sex ){ this.sno = sno; this.name = name; this.sex = sex; } public void show(){ System.out.println(sno +" "+this.name+" "+sex+" " +this.score+" "+classRoom); } public static void main(String[] args) { System.out.println(Student.classRoom); Student.classRoom = "503"; System.out.println(Student.classRoom); Student stu = new Student(7,"pseudo-ginseng","male",77); stu.sno = 5; //Student.sno = 6; stu.classRoom = "507"; stu.show(); Student stu2 = new Student(); stu2.show(); } }

The memory allocation diagram is as follows:

Summary: differences between static variables and non static variables:

  1. Different copies: static variable: 1 copy; Non static variable: one copy for one object
  2. Different storage locations: static variables: method area; Non static variables: in heap
  3. The time of memory allocation is different: static variable: when the class is loaded for the first time; Non static variables: when creating objects
  4. The life cycle is different. The life cycle of static variables and classes is the same; The life cycle of a non static variable is the same as the object to which it belongs
  5. Different calling methods
  • Static variables:   Called by class name   Student.classRoom, you can also call stu1.classroom through the object name = "301". It is not recommended
  • Non static variable: called by object name      stu1.name = "Xiao Zhang";

1.2. static method

  • Function of static method

                 Accessing static variables and static methods

  • Calling method of static method

                 Called by class name   Student.showClassRoom(); This method is recommended

                 Access by object name   stu1.showClassRoom();

  • may not

                 Non static variables cannot be accessed in static methods

                 Non static methods cannot be accessed in static methods

                 this cannot be accessed in static methods

                 Understanding: static variables and static methods are loaded when loading classes. At this time, objects may not be created, so non-static variables and non-static methods have not allocated space and cannot be accessed

  • sure

                 Static variables can be accessed in non static methods

                 Static methods can be accessed in non static methods

                Understanding: static variables and static methods are loaded when a class is loaded. After an object is created, non-static variables and non-static methods allocate space. At this time, static variables and static methods already exist and can be accessed

[example 2] static method

public class Student { //Member variable String name; int age; String sex; double score; static String classRoom;//103 !!! public static void showClassRoom(){ System.out.println(classRoom); //System.out.println(name);// Non static variable //shout();// Non static method //System.out.println(this); } public static void setClassRoom(String classRoom){ Student.classRoom = classRoom; } //Member method public void introduce(){ System.out.println(this.name+" "+this.age+" " +sex+" "+score+" "+classRoom); showClassRoom(); } public static void main(String[] args) { Student.showClassRoom(); Student.setClassRoom("r301"); Student.showClassRoom(); //Student stu1 = new Student("Xiao Wang", 20, "male", 98); Student stu1 = new Student("Xiao Wang",20,"male"); stu1.name ="Xiao Zhang"; stu1.classRoom ="r301"; stu1.showClassRoom(); } }

1.3. static code block

  • Summary 1: local code blocks
  1. Location: in method
  2. Quantity: multiple
  3. Execution sequence: execute in sequence
  4. The scope of variables defined in the local code block is limited to the current code block
  •   Summary 2: (member) code block
  1. Location: in class
  2. Quantity: multiple
  3. Execution sequence: execute in sequence
  4. Execution time: executed every time an object is created; Execute the code block before the construction method
  5. Function: rarely used in actual development; The common code in each construction method can be extracted into a code block; The anonymous inner class cannot provide a constructor. In this case, the initialization operation is placed in the code block
  •   Summary 3: static code block  
  1. Location: in class
  2. Quantity: multiple
  3. Execution sequence: execute in sequence
  4. Execution time: executed when the class is loaded for the first time, only once
  5. Function: assign initial values to static variables. It is often used in actual development. It is generally used to perform some global initialization operations, such as creating a factory and loading the initial information of the database

[example 3] static code block

public class Student { static { System.out.println("static code block 1"); } String name; static String classRoom;//103 !!! static { //name = "sdf"; classRoom = "r301"; System.out.println("static code block 2"); } public Student(){ System.out.println("-----Student()---------"); } public static void main(String[] args) { int n = 4;//local variable // {/ / local code block // int m = 5; // System.out.println(m); // } System.out.println(classRoom); new Student(); new Student(); } { //classRoom = "r301"; System.out.println(" code block 3"); } }

Operation in this section

  1. Differences and relations between static variables and non static variables
  2. Why can't static methods access non static variables and methods
  3. Execution timing and times of static code block

Section 2 package and import

2.1. package

  • Why use packages

         There are too many files, and there will be files with the same name. The computer's hard disk needs different levels of folders to store them;

         Package mechanism is an important means to manage classes in Java. During development, we will encounter a large number of classes with the same name. Through package, we can easily solve the problem of class name duplication and realize effective management of classes. In addition to the above considerations, it is also closely related to access rights.

  • How to define packages

         We manage classes through package. There are two main points in the use of package:

  1. Package name: the domain name can be written upside down, plus the module name, which is convenient for internal management.
  2. All package names are lowercase.

com.bjsxt.oop.object

cn.com.sina.video....

com.bjsxt.stumgr.dao

com.bjsxt.stumgr.dao.impl

  • How to use packages

         It is usually the first non annotative statement of a class.

         Must be in; ending.

  • Common Java packages

Common packages in Java

explain

java.lang

It contains some core classes of Java language, such as String, Math, Integer, System and Thread, and provides common functions.

java.awt

It contains several classes constituting the abstract window toolkits, which are used to build and manage the graphical user interface (GUI) of the application.

java.net

Contains classes that perform network related operations.

java.io

Contains classes that provide multiple input / output functions.

java.util

Contains utility classes such as defining system properties and using date calendar related functions.

matters needing attention

  • Add packages when writing projects. Do not use the default package.
  • Com.gao and com.gao.car, which have no relationship, are two completely independent packages. It just seems logically that the latter is part of the former.  

2.2. import

         If we want to use classes of other packages, we need to use import, so that we can call directly through the class name in this class. Otherwise, we need to write the full package name and class name of the class. After import, it is easy to write code and improve maintainability.

Key points for attention

  1. The default is the class and interface of the current package
  2. Java will import all classes under the java.lang package by default, so we can use these classes directly.
  3. Wildcards can be used, such as import com.bjsxt.oop.object. *; All classes and interfaces under the package will be imported (excluding child packages)
  4. If you import two classes with the same name, you can only use package name + class name to display the calling related classes:

java.util.Date date = new java.util.Date();

         Static import   import) is a newly added function in JDK 1.5. It is used to import static properties and static methods of specified classes, so that we can directly use static properties and static methods.  

[example 4] import and static import

import java.lang.reflect.Constructor; import java.util.Date; import java.util.*; import static java.lang.Math.PI; import static java.lang.Math.*; public class TestImport { public static void main(String[] args) { Date date = new Date(); java.sql.Date date2 = java.sql.Date.valueOf("19990-12-23"); List list; Set set; Map map; Constructor constructor; System.out.println(PI); System.out.println(sqrt(64)); System.out.println(pow(7, 2)); } }

2.3. Generate API documents using document comments

         IntelliJ IDEA itself provides good JavaDoc generation function and standard JavaDoc annotation conversion function. Its essence is to write annotations for classes, methods and other members that need to be exposed to users according to the annotation requirements of standard JavaDoc during code writing. Then use the function of IDEA to automatically call javadoc.exe (JDK's own tool) to automatically generate JavaDoc documents (hypertext format) according to the comments in the source code.

[example 5] using document notes

/** * Student class */ public class Student { /** * full name */ String name; /** * Age */ int age; /** * Gender */ String sex; /** * study */ public void study(){ } /** * examination * @param site place * @return fraction */ public double test(String site){ return 100; } }

  The main operation steps in idea are as follows:

Finally, the API help document shown in the figure can be generated.

Operation in this section

  1. Understand the function of package
  2. Common packages in Java and their functions
  3. Precautions for import

Section III encapsulation

       Encapsulation is one of the three characteristics of object-oriented. The reasonable encapsulation of the program makes the external call more convenient and more conducive to writing. At the same time, it is easier for implementers to modify and revise the code.

3.1. Lead in package

         If I want to watch TV, I just need to press the switch and change the channel. Is it necessary to understand the internal structure of TV? Is it necessary to touch the picture tube? In order to make it convenient for us to use the TV, the manufacturer encapsulates all the complex internal details and only exposes us simple interfaces, such as power switches. We don't need to worry about how to implement it internally. Similarly, when the clutch, accelerator, brake and steering wheel are exposed, the driver can drive without understanding the principle and maintenance.

         What needs to be known to the user is exposed, and all that does not need to be known to the user is hidden. This is encapsulation. To be professional, encapsulation is to combine the attributes and operations of the object into an independent whole, and hide the internal implementation details of the object as much as possible.

         Our programming should pursue "high cohesion and low coupling". High cohesion means that the internal data operation details of the class are completed by themselves, and external interference is not allowed; Low coupling is to expose only a small number of methods for external use, so as to facilitate external calls as much as possible.

Specific advantages of encapsulation in programming:

  1. Improve code security.
  2. Improve code reusability.
  3. "High cohesion": encapsulate details, facilitate modification of internal code and improve maintainability.
  4. "Low coupling": simplify external calls, facilitate the use of callers, and facilitate expansion and cooperation.

[example 6] code demonstration without encapsulation

class Person { String name; int age; public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } } public class Test { public static void main(String[ ] args) { Person p = new Person(); p.name = "Xiao Hong"; p.age = -45;//Age can be assigned arbitrarily in this way without any restrictions System.out.println(p); } }

         We all know that age cannot be negative or over 130, but if encapsulation is not used, age can be assigned to any integer, which obviously does not accord with our normal logical thinking.  

3.2. Permission modifier

         Java uses "access control characters" to control which details need to be encapsulated and which details need to be exposed. The four "access control characters" in Java are private, default, protected and public. They illustrate the encapsulation of object-oriented, so we should use them to minimize access rights as much as possible, so as to improve security.

         Their access rights are described in detail below. The scope of access rights is shown in the table.

  Access modifier

Modifier

Same class

In the same package

Subclass

All classes of all packages

private

*

default

*

*

protected

*

*

*

public

*

*

*

*

  1. Private means private, which can only be accessed by its own class
  2. default means that there is no modifier, and only classes of the same package can access it
  3. protected means that it can be accessed by classes in the same package and subclasses in other packages
  4. public means that it can be accessed by all classes in all packages of the project

Processing of members of class:

  • private access is generally used.
  • Provide corresponding get/set methods to access related properties. These methods are usually public modified to provide assignment and reading operations for properties (Note: the get method of boolean variable starts with is!).
  • Some auxiliary methods only used for this class can be modified with private. It is hoped that the methods called by other classes can be modified with public.

Class processing:

  • Class can only be decorated with public and default
  • Default: current package
  • public: all packages of the current project
  • Public class requires the same class name and file name. There can be at most one public class in a java file

[Example 7] code demonstration after encapsulation

class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; setAge(age); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { //Judge whether the age is legal before assignment if (age > 130 || age < 0) { this.age = 18;//Illegal default value 18 } else { this.age = age;//Only legal can be assigned to attribute age } } public int getAge() { return age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } } public class Test2 { public static void main(String[ ] args) { Person p1 = new Person(); //p1.name = "little red"// Compilation error //p1.age = -45; // Compilation error p1.setName("Xiao Hong"); p1.setAge(-45); System.out.println(p1); Person p2 = new Person("Xiaobai", 300); System.out.println(p2); } }

3.3. Packaging exercise

Based on the idea of object-oriented, a user-defined class is written to describe book information. Setting attributes include: book title, author, publisher name and price; Methods include: information introduction
requirement:
         1) Set the private access permission of the property, and access the property through the public get and set methods
         2) The limited price must be greater than 10. If it is invalid, you will be prompted
         3) Design and construct methods to assign values to attributes
         4) Information introduction method describes all the information of the book
         5) Write test classes, test objects of books and related methods (test data information is self-defined)

[example 8] encapsulate Book

public class Book { private String bookName;//title private String author;//author private String publisher;//press private double price;// public Book(){ //super(); } public Book(String bookName,String author,String publisher,double price){ this.bookName = bookName; this.author = author; this.publisher = publisher; //this.price = price; this.setPrice(price); } public void setBookName(String bookName){ this.bookName = bookName; } public String getBookName(){ return this.bookName; } public void setAuthor(String author){ this.author = author; } public String getAuthor(){ return author; } public String getPublisher(){ return publisher; } public void setPublisher(String publisher){ this.publisher = publisher; } public void setPrice(double price){ if(price < 15){ this.price = 10; System.out.println("The price must be greater than 10 yuan, which is 10 yuan by default"); }else{ this.price = price; } } public double getPrice(){ return this.price; } public void show(){ System.out.println("bookName="+bookName+",author=" +author+",price="+price+",publisher="+publisher); } public static void main(String[] args) { //Buy the first book Book book1 = new Book(); //book1.price = 3; book1.setBookName("DUKE OF MOUNT DEER"); book1.setAuthor("Jin Yong"); book1.setPrice(7); book1.setPublisher("tsinghua university press "); book1.show(); //Buy a second book Book book2 = new Book("The story of relying on heaven to kill Dragons","Jin Yong","tsinghua university press ",30); book2.show(); System.out.println(book1.getBookName()); } }

Operation in this section

  1. What are the functions of the four permission modifiers: private, default, protected, and public?
  2. Using the idea of object-oriented, write user-defined information to describe the dog. Setting attributes include: variety, age, mood and name; Methods include: call and run. requirement:
  1. Set the private access permission of the property, and access the property through the public get and set methods
  2. The limited mood can only be "in a good mood" and "in a bad mood". If the input is invalid, the default setting is "in a good mood".
  3. Set the constructor to assign a value to a property
  4. The method of calling and running needs to describe different ways of behavior according to the mood.
  5. Write test classes, test dog objects and related methods (test data information customization)

Operation effect diagram:

Section IV inheritance

         Inheritance is one of the three characteristics of object-oriented programming. It makes it easier to extend existing classes and model the real world.

4.1. Inheritance and its role

         Inheritance makes it easier to implement class extensions. For example, if we define human beings and then define Boy class, we only need to extend human beings. It realizes the reuse of code without reinventing the wheel (don't)   reinvent   wheels).

         From the literal meaning of English, extensions means "extension". A subclass is an extension of a parent class. Inheritance in the real world is everywhere. For example:

Figure 5-1 inheritance in the real world  

          Above, mammals inherit animals. It means that mammals have the characteristics of animals; In our programming, if we define a new Student class and find that the Person class already contains the properties and methods we need, the Student class only needs to inherit the Person class to have the properties and methods of the Person class.

  [Example 9] implement inheritance

public class Animal {//extends Object private String color;//colour private int age;//Age public Animal() { super(); } public Animal(String color, int age) { //alt+insert this.color = color; this.age = age; } public void eat(){ System.out.println("eating .........."); } public void sleep(){ System.out.println("sleeping............"); } public void introduce(){ System.out.println(color+" "+age); } } public class Dog extends Animal{ private String nickName;//nickname public Dog() { } public Dog(String color,int age){ } public Dog(String color,int age,String nickName){ // this.color = color; // this.age = age; super(color,age); this.nickName = nickName; } public void guard(){ System.out.println("Dog guarding......"); } } public class Cat extends Animal { private int eysSight;//vision public Cat() { super();//The parameterless constructor of the parent class is called by default } public Cat(String color, int age, int eysSight) { super(color,age); this.eysSight = eysSight; } public void grabMouse(){ System.out.println("Cat grab mouse.........."); } } public class Test { public static void main(String[] args) { Dog dog = new Dog("black",3,"Wangcai"); dog.eat();//Method inherited from parent class dog.sleep();//Method inherited from parent class dog.introduce();//Method inherited from parent class dog.guard();//Subclass specific methods Cat cat = new Cat("Decor",3,5);//alt+enter cat.eat(); cat.sleep(); cat.introduce(); cat.grabMouse(); } }

Key points of inheritance and use

  1. Parent classes are also called superclasses and base classes. Subclasses: derived classes, etc.
  2. There is only single inheritance in Java, not multiple inheritance like C + +. Multiple inheritance will cause confusion, making the inheritance chain too complex and the system difficult to maintain.
  3. A subclass inherits from the parent class and can get all the properties and methods of the parent class (except the construction method of the parent class), but it may not be directly accessible (for example, the properties and methods private to the parent class).
  4. If extensions is not called when defining a class, its parent class is java.lang.Object.

4.2. Method rewriting

         The method introduce() of the parent class can no longer meet the needs of the child class. What should I do? Similarly, toString() of Object class can no longer meet the requirements of Animal class and Dog class. What should I do? It can be solved by method override, or called method override.

[example 10] implementation method rewriting

public class Animal {//extends Object protected String color;//colour private int age;//Age public Animal() { super(); } public Animal(String color, int age) { this.color = color; this.age = age; } public void introduce(){ System.out.println(color+" "+age); } @Override public String toString() { //return super.toString(); return "Animal[color="+color+",age="+age+"]"; } } public class Dog extends Animal{ private String nickName;//nickname public Dog() { } public Dog(String color, int age){ } public Dog(String color, int age, String nickName){ // this.color = color; // this.age = age; super(color,age); this.nickName = nickName; } public void introduce(){ //this.introduce(); //super.introduce(); System.out.println(color+" "+this.getAge()+" "+nickName); } public void guard(){ //this.guard(); //super.guard(); System.out.println("Dog guarding......"); } @Override public String toString() { //return super.toString()+" "+nickName; return "Dog[name="+color+",age="+getAge()+ ",nickName="+this.nickName+"]"; } }

total

Method overloading and method rewriting (covering) are two important concepts in object-oriented. In fact, there is no relationship between the two concepts, but they are all about methods, which is easy to be confused after all. I have also made some generalizations and feel that I can distinguish these two concepts very well. I intend to explain it from two aspects: overall difference and detail difference.

branch

Overall difference: the main difference is that the problems solved are different, that is, the functions are different.

english

Different location

Different functions

heavy load

overload

In the same class

Provide multiple implementations and improve readability for a behavior in a class

rewrite

override

Between subclass and parent

The parent class method cannot meet the requirements of the child class. The child class meets the requirements through method rewriting

Difference in details: the declaration of a method from left to right includes permission modifier, method return value, method name, parameter list, thrown exception type, etc. The following explains the differences from these aspects

Modifier

Return value

Method name

parameter

Throw exception

heavy load

irrelevant

irrelevant

identical

Different

irrelevant

rewrite

Greater than or equal to

Less than or equal to

identical

identical

Less than or equal to

total

Overload instance: constructor overload and println() method overload

Rewrite instance: toString(), equals(), hashCode() of Object class can be overridden by subclasses

Optional

  1. Some methods use the final modifier and cannot be overridden. For example, wait() and notify() of the Object class
  2. Static methods cannot be overridden. In Java, if the parent class contains a static method and the subclass also contains a static method with the same return type, method name and parameter list, the subclass actually hides the method with the same name in the parent class instead of overriding it. Adding @ override annotation will report an error.

Operation in this section

  1. The role of inheritance
  2. Define the parent class Animal, Dog and Cat to inherit the Animal class
  3. Comparison between method rewriting and method overloading
  4. Rewrite toString() of Animal, Dog, Cat

25 September 2021, 08:30 | Views: 6811

Add new comment

For adding a comment, please log in
or create account

0 comments