20145326 Java Programming 4th Week of study summary

Source: Internet
Author: User

20145326 "Java Program Design" The 4th Week study summary textbook Learning content Summary

Sixth chapter

First, what is inheritance

1. Inheritance of common conduct

In object-oriented, subclasses inherit the parent class, avoiding duplicate behavior definitions. However, it is not necessary to avoid repeated definition of the behavior of using inheritance, abuse of inheritance resulting in procedural maintenance problems when the smell. How to correctly judge the timing of using inheritance, and how to use polymorphism after inheritance, is the focus of learning inheritance. In the book on the 158 pages of the example, magician in the bold part and swordsman in the corresponding program code is duplicated, repetition in the design is bad signal, if we want to change name, level, blood to another name, It is necessary to modify the swordsman and magician two classes, if there are more classes with duplicate program code, it is necessary to modify more classes, resulting in maintenance inconvenience. If you want to improve, you can promote the same program code to the parent class (Role). A new keyword "extends" is introduced here. It indicates that swordsman and magician will expand role behavior, that is, the act of inheriting role. Swordsman and magician can not only inherit role behavior, but also expand the behavior that the original role does not have. Inheritance is to avoid repeating multiple classes and defining common behavior. One of the benefits of inheritance is that if you want to change the name, level, and blood to other names, just modify Role.java, as long as the subclass that inherits role does not need to be modified. One thing to note here is that private members are inherited, except that subclasses cannot be accessed directly and must be accessed through the methods provided by the parent class.

2. Polymorphism and Is-a

In Java, a subclass can inherit only one parent class, and in addition to avoiding the repetition of the behavior definition, there is an important relationship between the subclass and the parent class that has a is-a relationship, which Chinese calls "is a" relationship. In the previous example, swordsman inherits role, so swordsman is a role. However, if you write code that does not pass: Swordsman Swordsman=new Role (), compiler is the grammar checker, to know why the program fragments can be compiled, why not compile, is to use themselves as a compiler, check the syntax of the logic is correct, the way is from = To the right of the number to read left. The translation is: "Role is a swordsman", which is obviously wrong, causing the compilation to fail. The compiler checks this type of syntax, one line at a time. if: Role role1=new swordsman (); Swordsman Swordsman=role1; this also fails compilation. The first line is no problem, translation is "Swordsman is a role", right. In the second line, because Role1 is the name of the role declaration, the second line translates "role is a swordsman", which is not necessarily, so compilation fails. If you want the program to stop, you can modify this: role Role1=new swordsman (); Swordsman swordsman= (Swordsman) Role1; the equivalent of having role play swordsman, This program code can be compiled. But this is not the case: Role role2=new Magician (); Swordsman swordsman= (Swordsman) Role2; Role2 reference is Magician, you have to let the magician disguised as a swordsman, This will be a mistake in execution. Using a (IS-A) principle, it is possible to determine when a compilation succeeds, when the compilation fails, and to act as a compiler shut-down syntax. The 165-page example shows us a polymorphic way of writing, and how does that benefit? Even if there are 100 roles, as long as they are inherited roles, you can use this method to show the blood volume of a character without needing to be overloaded as before, and the polymorphic notation obviously has a higher maintainability. What does polymorphism mean? Polymorphism is the use of a single interface to manipulate multiple types of objects, note that the interface here does not refer specifically to interface in Java, but refers to an actionable method on an object.

3. Redefining behavior

If there is a requirement now, please design the static () method to play the character attack animation, the first thing we think of is the Drawfight () method. However, for the Drawfight () method, only know that the passed in will be a role object, so the compiler can only check the method you call, role is not defined, obviously the current role does not define the fight () method, so the compilation error. Take a closer look at the fight () method of Swordsman and magician, their method signature is public void fight (), that is, the operation interface is the same, but the operation content is different, We can then elevate the fight () method to defined in the role class. The fight method is defined in the role class (), because the actual role of the attack, only subclasses know, so here the fight () method content is empty, no program code execution, only when swordsman inherit role, then fight () is defined. After inheriting the parent class, you define the same method deployment as the father, but the execution content is different, which is called redefining. Note that if the incoming drawfight () is swordsman,role reference to the Swordsman instance (reference 167 example), the operation is the method definition on the swordsman. If fight () is defined in the parent class, but fight () is defined in the subclass, it is not redefined fight (), but the subclass redefined a fight () method, which is a valid method definition that can be compiled, But we'll find out why Swordsman didn't wield a sword. Annotations are supported after JDK5, and one of the built-in standard annotations is @override, which indicates that a compiler check is required, that the method does not really redefine a method in the parent class, and if not, it causes a compilation error.

4. Abstract methods, abstract classes

Now there is a problem, you do not have any way to force or prompt the subclass must operate the fight () method, can only be told orally or in the document, but if someone did not communicate, did not read the document, or the document is missing it? If there is really no program code operation in a method block, you can use abstract to indicate that the method is an abstract method, which does not have to write {} blocks, directly ";" The end is ready. In a class, if there is a method that does not operate and is marked abstract, it means that the class definition is incomplete and that a class with incomplete definitions cannot be used to generate an instance. This is like a design drawing is incomplete and cannot be used to produce the finished product. Subclass if you inherit an abstract class, there are two approaches to abstract methods, one is to continue to mark the method as abstract, and the other is to manipulate the abstract method, which throws a compilation error if neither of these practices is implemented. Ii. Inheritance of grammatical details

1.protected Members

According to the 170-page example of the book, the definition of ToString () is not very convenient when obtaining a name, rank, and amount of blood, because the name, level, and blood in role are defined as private, so they cannot be accessed directly in the subclass, only through GetName (), Getlevel (), Getblood () to obtain. The name, level, and blood in role are defined as public, which in turn completely opens the access rights for name, level, and blood, and if you don't want to do this, just want subclasses to have direct access to name, level, and blood. They can be defined as protected. is declared as a member of the protected, the classes of the same package can be accessed directly, and classes in different packages can be accessed directly from the inherited subclass. If the method does not have the same name parameter, this can be omitted, but based on the readability of the program, a more this will be more clear. Java has three permission words, respectively, public, protected, private, although there are only three permission words, but there are four permission scopes, because there is no definition of the permission keyword, the default value is the package scope. Permissions according to small to distinguish, is private, no keyword, protected, public, if at first do not know which permissions to use, the first use of private, later as required to release permissions.

2. Redefining the details

Sometimes when you redefine a method, you are not completely dissatisfied with the method in the parent class, but want to do a bit of processing before and after the method in the parent class is executed. In Java, if you want to get a method definition in the parent class, you can add the Super keyword before calling the method. A parent class method that can be called with the Super keyword and cannot be defined as private! This is because it is restricted to use within a class only. To redefine a method, be aware that for method permissions in the parent class, only the widening cannot be reduced, the Wakahara member is public, and the child class is redefined as private or protected! Before JDK5, when redefining a method, the other part must be exactly the same as the method signature in the parent class, in addition to defining a keyword with a larger permission. After JDK5, when redefining a method, it can be compiled if the return type is a subclass of the method return type in the father. The static method is owned by the class, and if a static member of the same signature is defined in the subclass, the member belongs to the subclass, not redefined, and the static method is not polymorphic because the object is not individually used with static members.

3. Look again at the constructor function

If a class has an inheritance relationship, after the subclass instance is created, the initial process defined by the parent class is first performed, and then the initial process defined in the subclass, that is, the process of defining the parent class constructor is executed after the child class instance is created, and then the process of the subclass constructor definition is executed. Constructors can be overloaded, and multiple constructors can be overloaded in a parent class, and the parameterless constructor in the parent class is called by default if the subclass constructor does not specify which constructor to execute in the parent class (book 174 example). One thing to note here is that this () and super () can only be called, and must be performed on the first line of the constructor. If you define a constructor with parameters, you can also add a parameterless constructor, even if the content is empty, for future use of elasticity.

4. Look again at the final keyword

If you do not want to change the value of the variable after you specify the value of the variable, you can add a final qualification when declaring the variable, and if you or others inadvertently want to modify the final variable, a compilation error occurs. If the object data member is declared final, but is not explicitly used = specified value, that represents the setting of the deferred object member value, in the constructor execution process, must have the action to specify the value of the data member, or compile the error. You can also add the final keyword before class, if you use the final keyword definition before class, it means that the class is the last one, and no more subclasses, that is, cannot be inherited. When you define a method, you can also qualify the method as final, which means that the method was last defined, that is, the subclass cannot redefine the final method.

5.java.lang.object

In Java, subclasses can inherit only one parent class, and if the class is defined without inheriting any class using the extends keyword, it must be inherited java.lang.Object. Any class that goes back to the topmost parent class must be java.lang.Object, that is, all objects in Java, which must be "an" object. Any type of object can be referenced using the name of the object declaration. What good is this, if there is a need to use an array to collect a variety of objects, then why the declaration type? The answer is object[]. The ToString () method we saw earlier and the Equals () method are all methods defined on the object. Java.lang.Object is the top-level father of all classes, which represents the method defined on object, and all objects are inherited and can be redefined as long as they are not defined as the final method. The instanceof operator, which can be used to determine whether an object is created by a class, the left operand is an object, the right operand is a class, and when the instanceof is used, the compiler will also be helpful to check whether the left operand is in the inheritance schema of the right operand type, the execution period, Not only the left operand object is directly instantiated for the right operand class to return true. Instanceof also returns true as long as the left operand type is a subtype of the right operand type.

6. About garbage collection

Creating an object takes up memory, and if an object is no longer being used in the program execution process, the object is simply a waste of memory. For objects that are no longer useful, the JVM has a garbage collection mechanism (GC), and the collected garbage objects occupy a memory space that is freed by the garbage collector. In the execution process, objects that cannot be referenced by variables are garbage objects identified by GC. The execution process is specifically a thread, and the only thread you are currently exposed to is the main course after the entry point of the main () program, where the garbage collection itself is complex and different requirements have different methods.

7. Look at the abstract class again

Writing programs often seem unreasonable but have to be completed. Some unreasonable demand, itself is indeed unreasonable, but some seemingly unreasonable demand, in fact, can be solved by design. In the 186 pages of the book 3 examples, the first example of the class definition is not complete, print (), println () and Nextint () are abstract methods, because the boss has not decided in which environment to execute the game, so how to display the output, get user input can not be manipulated, But we can manipulate the process of guessing numbers first, although it is an abstract method, but it can still be called in the Go () method. In fact, as long as the creation of an instance of Consolegame, the execution of the Go () method calls to print (), println () and Nextint () and other methods, are executed consolegame defined in the process, the complete guess the number of games is done.

Seventh Chapter

First, what is interface

1. Interface definition Behavior

Take the book 195 pages for example, the boss today wants to develop a sea paradise game, all things will swim, talk about swimming things, first think of fish, the last chapter and just learned inheritance, also know that inheritance can use polymorphism, so will be defined in fish class has a swim () behavior. But in fact, each species swims differently, so the swim () is defined as abstract. The boss also said why are all fish, people can swim ah, so then define human class inherit fish, but human inherit fish? Wouldn't it be strange, right, that the program would not complain about anything, so far, the program can be executed, but there are logical or design unreasonable places. Java can only inherit one father, so it reinforces the restriction of a "is a" relationship. "Everything" will "swim", which means that "swimming" is a "behavior" that can be owned by everything, not "something". For define behavior, you can use the interface keyword definition in java. Interfaces can be used to define behavior but do not define operations, in the book 197 page example, the swim () method does not operate, directly marked as abstract, and must be public, objects must operate swimmer interface if they want to have swimmer defined behavior. class to operate the interface, you must use the Implements keyword, to operate an interface, the interface defined in the method has two methods, one is the method defined in the Operation interface, and the second is to re-mark the method as abstract. In Java semantics, inheritance will have a "is a" relationship, and the operating interface means "owning behavior".

2. Polymorphism of behavior

After using the interface definition behavior, it is also time to compile the program to see what is the legal polymorphic syntax. such as: Swimmer swimmer1=new Shark (); This code is right. The way to judge is "right is not the left side of the act." So the translation came to be "sharks can swim." "Absolutely right. And for the following situation: Swimmer swimmer1=new Shark (); Shark shark= (Shark) Swimmer; without the parentheses, the compilation fails. Because objects with swimmer behavior are not necessarily shark, they cannot be compiled. The bracketed content is to let the program shut up, there is swimmer behavior of the object, not necessarily shark, but I now want to let swimmer play shark! , this can be compiled, the execution period is really swimmer also reference shark instance, so there is no error. But if this is the case, not: Swimmer swimmer1=new Human (); Shark shark= (Shark) Swimmer; In the second row, Swimmer actually refers to Human instances, which cannot be compiled. In your design, the things that can swim have swimmer behavior, all operate the swimmer interface, as long as the operation swimmer interface object, you can use the example (201 pages) in the Doswim () method. Maintainability obviously improved a lot.

3. Address demand changes

We all know that writing procedures should be flexible and maintainable. But this is really an abstract problem, starting from the simplest definition, if you add new requirements, the original program does not need to be modified, just to write a program for the new requirements, it is flexible, maintainable program. In Java, a class can manipulate more than two classes, that is, more than two kinds of behavior. Of course, the demand is endless, the original program framework may indeed meet certain needs, but some of the requirements may be more than the original structure of the flexibility, how to design in the beginning to be flexible, it must rely on experience and analysis. Perhaps you have designed an interface in anticipation of some requirements, but from the program development to the end of the life cycle, the interface has never been manipulated, or only one class has manipulated the interface, then the interface may not exist, and your prior assumptions may be over-forecasting requirements. It is easy to reaching a program if you want to modify it under a bad architecture. That's right! In Java, an interface can inherit from another interface. Changes in demand, and the architecture is likely to change as a result. Good architecture in the modification, in fact, not all of the program code is affected, this is the importance of design.

Second, interface syntax details

1. Default of the interface

In Java, you can use interface to define the behavior and appearance of abstractions, such as methods in an interface that can be declared public abstract. such as: public interface swimmer{publicly abstract void swim ();} The method in the interface is not operational, it must be open and abstract, for convenience, you can also omit the The compiler will automatically add public abstract to your application. There is a good example in the bottom corner of the 208 page of the book, this code must not compile successfully, because execute () defined in action is in fact the public abstract, and the some class does not write public when it operates the Execute () method. So this is the default package permission, so that the public method in action is reduced to the package permissions, so the compilation fails, you must change the some class's execute () to public before compiling. Constants can also be defined in interface. As in public interface action{public static final int A=1;}java is often seen in interfaces that define such constants, called enumeration constants. In interface, you can define only the enumeration constants for public static final. For convenience, write the program can be omitted, the system will automatically help you write public static final, so in the interface enumeration constants, be sure to use = Specify the value, otherwise you will compile the error. It is also possible to define enumeration constants in a class, but be sure to write the public static final explicitly. Class can manipulate more than two interfaces, and if there are two interfaces that define a method, what happens to classes that operate two interfaces? On the surface of the program, there is no error, so compile. But think about it, if it means different behavior, there should be different ways of doing it, and the Execute () method of some and other is different in name. If the same behavior is expressed, it is possible to define a parent interface, in which the Execute () method is defined, and some and other inherit the interface, each defining its own dosome () and DoOther () methods (example 212 in the book). Interfaces can inherit other interfaces, or they can inherit more than two interfaces at the same time, and also use the extends keyword, which represents the behavior of inheriting the parent interface. After JDK8, if the method defined in the parent interface has an operation, it also represents an operation that inherits the parent interface.

2. Anonymous inner class

There is often a need to temporarily inherit a class or manipulate an interface and establish an instance, because such subclasses or interface operations classes are used only once and do not need to define names for these classes, and anonymous internal classes can be used to address this requirement by using an anonymous inner class: New father () | interface () {//Class ontology operation}; Before JDK8 occurs, if you want to access a local variable in an anonymous inner class, the local variable must be final, or a compilation error will occur. The life cycle of a local variable tends to be shorter than the object, like returning an object after a method call, the local variable life cycle is over, and then an error occurs when the object tries to access the local variable, and the Java practice is to use the pass value, which in fact creates a new variable referencing the original object in an instance of the anonymous inner class.

3. Enumerate constants using enum

Since JDK5, the enum syntax has been added and can be used to define enumeration constants. According to the example on page 217 of the book, in the process of defining enumeration constants using an enum, the enum actually defines a special class, inheriting java.lang.Enum, but this is handled by the compiler, and the direct writer inherits the Enum class and is rejected by the compiler. The action defined by the enum in the example is actually a class, and the stop, right, left, up, and down constants enumerated in the enum are actually public static final and the action instance. You cannot compose a program to instantiate an action directly, because the constructor permission is set to private, only the action class can be materialized. But we can use this action to declare the type. The action parameter in the play () method is declared as the action type, so only accept Action.stop, Action.right, Action.left, Action.up, The incoming Action.down, unlike the previous play () method, can pass in any int value, and case can only enumerate action instances, so instead of the previous example, you must use default to check at execution time, and the compiler will perform type checking at compile time.

Problems in teaching materials learning and the solving process

The sixth chapter is mainly about inheritance and polymorphism, the content is actually quite simple, and not so abstract, the inheritance of the "Father and son" of the idea and "is-a" concept I was particularly impressed, which is also the breakthrough of understanding. The code compiles pretty well, too. Polymorphism is the use of a single interface to manipulate multiple types of objects, note that the interface here does not refer specifically to interface in Java, but refers to an actionable method on an object. The seventh chapter is mainly about the interface, the interface keyword is "Defining the behavior", and the Implements keyword is the meaning of "own behavior". Have some behavior through an interface. The two chapters of the concept are almost mastered, but also the code on the book is knocked over, feel no big problem, very happy ~! Code is hosted ~

Problems in code debugging and the resolution process

In the process of tapping the code, most of them are quite smooth, there is a small part due to my carelessness, do not pay attention to the case of a variety of reasons such as the compilation failed, but after the correction, but also successfully through the compilation. After knocking over the code in the book, I felt a deeper understanding of the two chapters. The code is all managed successfully!

Other (sentiment, thinking, etc., optional)

In fact, the first three chapters of Java is the introduction of some basic knowledge concepts, played a role in the introduction. The difficulty is not particularly large. But the fourth chapter begins to touch the core knowledge of Java programming. Last week spent a considerable amount of time to complete the task, although tired, but very enjoyable, very happy. Also gave me the motivation to study for the fourth week. The task of the four weeks is to learn the sixth and seventh chapters, the content of the difficulty and fourth fifth chapter actually almost, see the first time of course feel that there are many places do not understand, very unfamiliar. This time will be quiet, learning Java is not to write a blog to cope with teachers, there is no need, the relationship between teachers and students should be the relationship between the fitness instructor and fitness students, to learn the process carefully, find happiness, discover the true meaning of learning. Ultimately, it's good to have a virtuous circle. That's what I was looking for when I started learning java. I now is to read the book first, and then do not understand all do mark, and then see Bi Xiangdong Teacher's video, and then read, and constantly find problems, constantly solve problems, constantly have new feelings and harvest, the final finishing thoughts, will be recorded in the blog, and teachers and classmates to share. I think this is also Lou Jia Peng's original intention of the teacher ~ This is also our request and expectations! The highest level of learning is to learn in happiness, to find happiness in learning. Calm down, no purpose and purpose, continue to work! ~ Nothing is difficult, is afraid of the conscientious. Anything, everything is difficult at the beginning, but as long as the stick down, will certainly benefit!!!

Learning progress Bar
Lines of code (new/cumulative) Blog volume (Add/accumulate) Learning time (new/cumulative) Important growth
Goal 3500 rows 20 articles 300 hours
First week 120/120 1/1 14/14
Second week 340/460 1/2 14/28
Third week 200/660 1/3 14/42 Learned the managed code, learned to use the construction model method to understand the class and object this part of knowledge.
Week Four 320/980 1/4 14/56

20145326 Java Programming 4th Week of study summary

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.