20172319 "Java Programming Tutorial" Week 7 Learning Summary

20172319 2018.04.11-16

"Java Programming Tutorial" Week 7 Learning Summary

content


Textbook learning content summary

Chapter 9 Succession:

  • Create subclasses:
    parent class (superclass, base class): people;
    subclasses (subclasses, derived classes): yellow, black, white; the
    parent class provides a general framework, and the subclass based on this framework also includes Different characteristics ( eg: colors of different races);
    use to extendsindicate that the new class is derived from the existing class, which is equivalent to "yes";
    the subclass inherits the method definitions and variable declarations in the parent class == these methods and variables are in the subclass ( Note: Subclasses can define methods and variables to highlight their characteristics ; inheritance is unidirectional ), classes do not allow multiple inheritance .
    (1) protected modifier:
    semi-public, allowing subclasses and other classes in the same package to reference methods and variables in the class without destroying its encapsulation characteristics . Note: There must be a protected modifier before the methods and variables that can be referenced, and the subclass will not inherit the constructor of the parent class . Adding # in front of methods and variables in UML class diagrams indicates that the protected modifier is applied; subclasses cannot refer to private members of superclasses by name . (2) super reference: call the constructor of the parent class, (generally it will be in the first line of the constructor of the subclass)——




    super(需要访问的变量)Make sure that the parent class initializes its own variables before the subclass executes the constructor ;
    advantage: when the constructor is used in the parent class to change the way variables are set, there is no need to go to the subclass's constructor to modify it.
    (3) Multiple inheritance:
    It is used when two or more classes are needed to describe the object;
    Disadvantage: When encountering members with the same name in the parent class, it is not known which one to inherit.
  • Overriding method:
    In subclasses, methods inherited from the base class can be overridden as needed; the
    overriding method must have the same method name, parameter list and return type as the
    overridden method ; Stricter access permissions for overridden methods
    eg: When the parent class member permission is private, the method cannot be overridden ;
    Note: Subclasses of methods modified by the final modifier cannot override them
    . Advantages: Ensure that subclasses use a specific method.
    Shadow variable:
    A variable with the same name as the parent class is defined in the subclass. The definition is legal and should be avoided in principle.
    Disadvantage: Not easy to understand the code.
  • Class hierarchy:
    parent class derives subclasses, and subclasses can derive one or more other subclasses (unlimited number of subclasses and layers);
    siblings: two subclasses of the same parent class;
    inheritance is transitive; It is reasonable to place common features at a higher level of the class hierarchy.
    (1) Object class: at the top level in the class hierarchy, if a class definition does not extendsindicate its parent class, the default parent class is Object; any object in the program can call the public method in Object;
    Object class Commonly used methods:
    equals() Equivalent to ==; toString()returns a string representing the object.
    (2) Abstract class:
    a class declared with the keyword abstract may not contain operation methods; in the UML class diagram, the abstract class name is represented in italics;
    if a class contains one or more abstract methods, the class must Specify as abstract; cannot use and modifier
    for abstract methodsfinalstatic
    : subclasses cannot override the finalmethod, staticand can be used without instantiation, but there is no method body in the method, so the method is meaningless.
    (3) Interface hierarchy:
    The interface inherits the interface, and the subclass inherits the abstract methods and constants of the parent class.

  • Visibility:
    The private members of the parent class can be indirectly accessed by the child class.
  • Design of inheritance relationship between classes:
    (1) Summary of inheritance relationship:
    1. Sort out the "yes" relationship in each derivation, and make it more specific each time;
    2. The design structure is conducive to the reuse of classes and potential software reuse in the future ;
    3. Public properties should be placed at a higher class level as much as possible;
    4. Appropriately rewrite methods
    according to requirements; 5. Add new variables according to requirements ( try to avoid shadow variables );
    6. Classes manage themselves and perform appropriate super Reference and overriding methods;
    7. Interfaces simulate multiple inheritance;
    8. Consider forward-looking structures;
    9. Subclasses should appropriately override common methods;
    10. Use abstract classes to define public class interfaces for lower-level classes;
    11. Use decoration with caution symbol.
    (2) Inheritance restrictions:
    finalModifiers: for methods - restricting overriding;
    for classes - restricting inheritance.

Back to Contents


Problems and Solving Processes in Teaching Materials Learning

  • Question 1: Classes do not support multiple inheritance?
  • Solution: The multiple inheritance that I said is good, and then it is clearly not supported.Contradiction? ? ? Conflict point: I don't know which one to inherit when I encounter members with the same name in two parent classes.Simple, just change the method name!Appropriate names are conducive to the understanding of the code. After a long time, if you find out the code with the changed name alone, if you have no impression of it, it will become difficult to recognize it, so it will not work; (A is Parent class, BC is a subclass, D inherits BC) first C extendsB then D and then extendsC,emmmmm, seems to make sense,It's totally uselessBC inherits A and develops its own characteristics on a certain basis. C inherits B, and the method with the same name will be rewritten. In the end, D only inherits C. (B=yellow race, C=white race, expected D=mixed race; D=white race as above)How to do it?Java can implement multiple interfaces. The methods in the interface are abstract, and it has no method body, so it cannot be implemented simply by creating an object and calling the method. But that's not to say that the interface implementation is the perfect solution; it has the disadvantage of not being able to share the implementation.
  • Originally just to share code across the inheritance hierarchy, now it is necessary to generate a separate object, and each method call must be delegated to this object, which is really unreasonable, and the execution efficiency is not high.
    ——"The Program World of Yukihiro Matsumoto"

  • Question 2: About shadow variables
  • Solution: The book simply said that this thing is similar to the rewriting method, which is a bit mysterious. I did some research and saw this.
public class ParentClass 
{ 
   public int i = 10; 
}

public class SubClass extends ParentClass 
{ 
   public int i = 30;
}   

public static void main(String[] args) 
{ 
   ParentClass parentClass = new SubClass();  
   SubClass subClass = new SubClass(); 
   System.out.println(parentClass.i + subClass.i); 
    
}

??? What the hell is in the created object??? I went to play with it myself



public class h1
{
    protected int i = 10;
}

public class h2 extends h1 
{
    public int i = 20;
}

public static void main(String [] args)
{
        h1 a = new h2();
        h2 b = new h2();

        System.out.println(a.i+b.i);
}

结果输出是30,影子变量并不像是重写数据,它是属于子类的一个变量,名字与父类继承的重合,相当于子类有两个变量i1=10;i2=20,**所以说要尽量避免使用,** 这对代码的理解增加了难度。  

a is an object of h1 and an object of h2,
then when calling the method, it is called according to the actual type of the object, and the
actual type is h2, so the method of the subclass is called, that is, i.
Accessing member variables is different. When it is h1, it accesses the member variable i=10 of the parent class. If it is
converted to h2, it accesses the member variable i=20 of the subclass.
Shadow variables != override, but co-exist and hide from each other.

  • Question 3: About abstract classes and interfaces
  • Solution: It seems that an abstract class can not only contain non-abstract methods , but also declare data in addition to constants. There is no other difference from an interface except that it is a bit redundant to define such a class additionally. It seems like this, but it is not:
    the interface can actually be regarded as a special abstract class, and the abstract class can be said to be the definition of "essence", so that the subclass does not need to redefine the public methods of the quality (under the derivation of the animal class). There is no need to define them as animals); the interface can be understood as a kind of "behavior", and the "bark" issued by cats and dogs is different. In order to realize their different behaviors, the "bark" can be defined through the interface Methods.

  • Question 4: Derivation of interfaces - useful?
  • Solution: Implementing an interface requires implementing all methods in its definition, if the interface uses inheritance. For example: each interface defines a method, and what needs to be implemented is the interface that has been inherited more than 100 times. To implement it, you need to open all the parent classes to view the member names defined by the interface.Afraid not to be exhausted!, It is better to define more than 100 methods directly in an interface, so that programming is more efficient.
    In fact, this is related to the fact that it is an abstract class: if all the methods are placed in the same interface, the prescribed behavior will inevitably make people feel a bit too much;
    1. A collection should define both the behavior of an ordered collection and the behavior of an unordered collection. , it is necessary to define the behavior of a collection with repeated elements, and also to define the behavior of a collection without repeated elements. Assuming that there is only one method to define the behavior of a collection, how to implement this method. Don't say add a lot of if else judgment statements. If a new collection type is added at this time, should you add an if else statement? This is undoubtedly a terrible method.
    2. The hierarchical interface generated by interface inheritance, hierarchical analysis, and clear responsibilities, Set is Set, List is List, whichever structure you want to implement can directly implement the corresponding interface. From another point of view, through interface inheritance, you can redefine the behavior already defined by the upper layer, and it will not affect the behavior of other interfaces at the same level.

Back to Contents


Problems and solutions in code debugging

  • Problem 1: Error with super reference
  • solve:

Back to Contents


code hosting

Back to Contents


Summary of last week's exam mistakes

Back to Contents


Others (perception, thinking, etc., optional)

Back to Contents


learning progress bar

Back to Contents


References

Back to Contents

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324768084&siteId=291194637