20145216 Shi Yao "Java program Design" 4th Week Study Summary

Source: Internet
Author: User

20145216 "Java Program Design" 4th Week Study Summary Textbook study summary sixth chapter inheritance and polymorphism 6.1 what is inheritance
  • Inheritance basically avoids the repetition of defining common behaviors among multiple classes.

  • In Java, when inheriting with the extends keyword, the private member is also inherited, except that the subclass cannot be accessed directly and must be accessed through the methods provided by the parent class (if the parent is willing to provide access methods). Such as:

    public class SwordsMan extends Role{  public void fight()     {         System.out.println("挥剑攻击");     }   }
  • Example of inheritance:

     public class rpg1{public static void Main (string[] args) {demoSwordsMan1 ();    DemoMagician1 ();       } static void DemoSwordsMan1 () {SwordsMan1 swordsMan1 = new SwordsMan1 ();       Swordsman1.setname ("Justin");       Swordsman1.setlevel (1);       Swordsman1.setblood (200);    System.out.printf ("Sword: (%s,%d,%d)%n", Swordsman1.getname (), Swordsman1.getlevel (), Swordsman1.getblood ());       } static void DemoMagician1 () {Magician1 magician1 = new Magician1 ();       Magician1.setname ("Monica");       Magician1.setlevel (1);       Magician1.setblood (100);    System.out.printf ("Magician: (%s,%d,%d)%n", Magician1.getname (), Magician1.getlevel (), Magician1.getblood ()); }}
  • Inheritance benefits: 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.

  • In Java, subclasses can inherit only one parent class, and inheritance has an important relationship, that is, there is a is-a relationship between the subclass and the parent class, and Chinese is called a "is one" relationship.

  • Check that the polymorphic syntax logic is correct by reading from the right to the left and not to the left (the right type is not a subclass of the left type)? If it does not compile the failure, if you add the play (Cast) syntax, the compiler will let the program code through the compilation, but the consequences are self-responsible, that is, to play the failure, execution throws classcastexception.

  • Polymorphism is the operation of multiple types of objects using a single interface.

  • After inheriting the parent class, you define the same method deployment as in the parent class, but the execution is different, which is called redefining. Such as:

Parent class:

    public class Role3    {      ...      public void fight()        {           //子类要重新定义fight的实际行为        }    }

Sub-class:

  public class SwordsMan3 extends Role3 {public void Fight () {System.out.println ("sword-wielding attack"); }    }   
    • If you label @override before a method in a subclass, indicating that a compiler check is required, the method does not really redefine a method in the parent class, and if not, it throws a compilation error.

    • If there is really no code manipulation in a method block, you can use abstract to mark the method as an abstract method, which does not have to write {} chunks, directly ";" to the end.

    • Subclass if you inherit an abstract class, there are two ways to abstract a method: one is to continue to mark the method as abstract, and the other is to manipulate the abstract method.

6.2 Inheritance Syntax Details
    • is declared as a member of the protected, classes in the same package can be accessed directly, and classes in different packages can be accessed directly from the inherited subclass. Such as:

Parent class:

    public abstract class Role5    {       protected String name;       protected int level;       protected  int blood;       ...略    }

Sub-class:

    public class SwordsMan5 extends Role5    {       ...       public String toString()       {            return String.format("剑士 (%s,%d,%d",this.name,this.level,this.blood);       }    }
  • There are public, protected, and private three permissions keywords in Java, but there are actually four permission scopes:

  • In Java, if you want to get a method definition in the parent class, you can add the Super keyword before calling the method. Such as:

    public class SwordsMan6 extends Role6{   ...   @Override   public String toString()   {       return "剑士" + super.toString();   }}
  • To redefine a method, be aware that for method permissions in the parent class, you can only expand but not shrink.

  • If you do not specify which function in the parent class is executed in the subclass constructor, the parameterless constructor in the parent class is called by default.

  • This () and super () select only one call and must be executed on the first line of the constructor.

  • If the final keyword definition is used before class, then 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.

  • 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.

The seventh chapter interface and polymorphism 7.1 what is interface
  • For define behavior, you can use the interface keyword definition in java. Such as:

    public interface Swimmer1{    
  • Interfaces can be used to define behavior but do not define operations.

  • class to manipulate interfaces, the Implements keyword must be used. When manipulating an interface, there are two ways of handling the methods defined in the interface: one is the method defined in the Operation interface, and the other is to mark the method as abstract again. such as: (The second method)

    public abstract class Fish1 implements Swimmer1{    protected String name;    public Fish1(String name)    {        this.name = name;    }    public String getName()    {        return name;    }    @Override    public abstract void swim();}
  • In terms of Java semantics, inheritance will have a "is a" relationship, the operating interface means "own behavior", but there is no "is a" relationship.

  •  public class Seaplane3 implements swimmer1,flyer3{private String name;    Public Seaplane3 (String name) {this.name = name;    } @Override {System.out.printf ("sea plane%s in flight%n", name);    } @Override public void Swim () {System.out.printf ("sea plane%s sailing sponge%n", name); }}
  • In Java, a class can inherit a class from a colleague and manipulate some interfaces. Such as:

    public class FlyingFish3 extends Fish1 implements Flyer3{    public FlyingFish3(String name)    {        super(name);    }    @Override    public void swim()    {        System.out.println("飞鱼游泳");    }    @Override    public void fly()    {        System.out.println("飞鱼会飞");    }}
  • In Java, an interface can inherit from another interface, that is, inherit the parent interface behavior, and then define the behavior in the sub-interface. Such as:

Parent class:

    public class Boat4 implements Swimmer1    {        protected String name;        public Boat4(String name)        {            this.name = name;        }        @Override        public void swim()        {            System.out.printf("船在水面 %s 航行%n", name);        }    }

Sub-class:

    public class Submarine4 extends Boat4 implements Diver4     {        public Submarine4(String name)        {            super(name);        }        @Override        public void dive()        {            System.out.printf("潜水艇 %s 潜行%n",name);        }    }
7.2 Interface Syntax Details
  • 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.

  • When a method in an interface is not operational, it must be public and abstract.

  • To enumerate constants in an interface, be sure to use = to specify values. And the interface enumeration constant must be public static final.

  • 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.

  • If there is a need to temporarily inherit a class or manipulate an interface and establish an instance, such subclasses or interface action classes are used only once and do not need to define names for these classes, which can be solved by using anonymous internal classes. The syntax for an anonymous inner class is:

    new 父类()|接口(){         //类本体操作};
  • enum actually defines the class, and the enumerated constants in the enum are actually public static Final, and is an instance of an enumeration type, it is not possible for the writer to instantiate the enumeration type directly because the constructor permission is set to private, as long as the class can be instantiated. such as:

    import static java.lang.System.out;public class EnumGame{    public static void main(String[] args)    {        play(EnumAction.RIGHT);        play(EnumAction.UP);    }    public static void play(EnumAction action)    {        switch (action)        {            case STOP:                out.println("播放停止动画");                break;            case RIGHT:                out.println("播放向右动画");                break;            case LEFT:                out.println("播放向左动画");                break;            case UP:            out.println("播放向上动画");                break;            case DOWN:            out.println("播放向下动画");                break;        }    }}
Problems in teaching materials learning and solving process problems:

In combination with teaching materials, video and teacher's blog learning guidance learned the sixth to seventh chapter, found that the teacher gave the study questions-interface and abstract class difference is still unclear.

Resolution process:

Baidu through the Internet, I finally understand the interface and the difference between the abstract class, the following is the information I find based on the summary of the two differences:

  • The difference at the grammatical level

    1、抽象类可以提供成员方法的实现细节,而接口中只能存在public abstract方法;2、抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是public static final类型的;3、一个类只能继承一个抽象类,而一个类却可以实现多个接口。
  • The difference at design level

    1、抽象类是对一种事物的抽象,即对类抽象,而接口是对行为的抽象;抽象类是对整个类整体进行抽象,包括属性、行为,但是接口却是对类局部(行为)进行抽象。2、对于抽象类,如果需要添加新的方法,可以直接在抽象类中添加具体的实现,子类可以不进行变更;而对于接口则不行,如果接口进行了变更,则所有实现这个接口的类都必须进行相应的改动。          
Problems in code debugging and resolving process issues:

Since many of the sample codes in the textbook have the same class names, I have numbered them after the class name, and I end up with an error when I finish typing the code:

Resolution process:

After reviewing the error code repeatedly, I found that the claim type (Role) in the code was not consistent with the class name (Role1) of the parent class, so I made the following modifications:

Last run to get the correct result:

Summarize:

After the class name is numbered, although it solves the problem of duplicate class name, it is particularly error-prone when knocking code, because many program code is related, must always keep the name of the class and reference at the time of creation consistent, so be careful when knocking the code, and first understand the meaning of each line of code, This allows you to avoid errors in your code as much as possible.

This week's code hosting

Other (sentiment, thinking, etc., optional)

This week mainly learn the inheritance and interface of the relevant knowledge points, although the content is more, for me also has a certain difficulty, but after the repeated study of the textbook and pondering, still can slowly understand and grasp, of course, I also have to understand the meaning of the code and irritability, but also want to directly follow the code on the book to Knock, Give up understanding do not understand the content, but calm down, or decided to learn this course, in fact, the teaching material is very detailed, code examples are also related to our familiar content, such as the sixth chapter is the role of the game, the seventh chapter is the development of a sea paradise game, there are class diagram and other picture interpretation, these are convenient for my understanding , so, although there are many difficulties in learning Java, but as long as they do not give up can solve the problem.

Learning progress Bar /Cumulative) new/cumulative)
lines of code (newBlog volume (Learning time (new/cumulative) Important growth
Goal 4500 rows 30 Articles 350 hours Be able to use Java freely
First week 150/150 2/2 15/15 Learn basic Java-related knowledge
Second week 200/350 1/3 20/35

Learn the basic syntax of Java

Third week 450/800 1/4 25/60

Learn about object and package knowledge

Week Four 687/1487 1/5 30/90

Learn about inheritance and interface knowledge

Resources
    • Java Learning Notes (8th Edition)
    • Java Learning Note (8th Edition) Learning Guide
    • ...

20145216 Shi Yao "Java program Design" 4th Week 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.