11_java Object-oriented _ 11th day (interface, polymorphism) _ Handout

Source: Internet
Author: User
Tags modifier

Introduction of today's content
1. Interface
2. polymorphic

01 Concept of the interface
* A:接口的概念    接口是功能的集合,同样可看做是一种数据类型,是比抽象类更为抽象的”类”。    接口只描述所应该具备的方法,并没有具体实现,具体的实现由接口的    实现类(相当于接口的子类)来完成。这样将功能的定义与实现分离,优化了程序设计。    请记住:一切事物均有功能,即一切事物均有接口。
02 Definition of the interface
    • A: Definition of the interface
    •   与定义类的class不同,接口定义时需要使用interface关键字。  定义接口所在的仍为.java文件,虽然声明时使用的为interface关键字的编译后  仍然会产生.class文件。这点可以让我们将接口看做是一种只包含了功能声明的特殊类。
    • B: Define the format
    •   public interface 接口名 {      抽象方法1;      抽象方法2;      抽象方法3;  }
    • C: Define Steps
    •   使用interface代替了原来的class,其他步骤与定义类相同:  接口中的方法均为公共访问的抽象方法  接口中无法定义普通的成员变量
Implementation class for the 03 interface
    • A: Class-to-interface relationships
    •   类与接口的关系为实现关系,即类实现接口。实现的动作类似继承,只是关键字不同,实现使用implements。  其他类(实现类)实现接口后,就相当于声明:”我应该具备这个接口中的功能”。实现类仍然需要重写方法以实现具体的功能。
    • B: Class implements the format of the interface
    •   class 类 implements 接口 {      重写接口中方法  
    • C: Precautions
    •   在类实现接口后,该类就会将接口中的抽象方法继承过来,此时该类需要重写该抽象方法,完成具体的逻辑。  接口中定义功能,当需要具有该功能时,可以让类实现该接口,只声明了应该具备该方法,是功能的声明。  在具体实现类中重写方法,实现功能,是方法的具体实现。
Features of member variables in the 04 interface
    • A: Characteristics of Member variables
      • A variable can be defined in a interface, but the variable must be decorated with a fixed modifier, public static final so the variable in the interface is also called a constant, its value cannot be changed. We'll explain the static and final keywords later
    • B: Case
    •   interface Demo { ///定义一个名称为Demo的接口。      public static final int NUM = 3;// NUM的值不能改变  }
Features of member methods in 05 interfaces
    • A: Characteristics of Member methods

      • A method can be defined in a interface, and the method has a fixed modifier, public abstract
      • A subclass must overwrite all of the abstract methods in the interface before it can be instantiated by the child class. Otherwise, the subclass is an abstract class.
    • B: Case
    •   interface Demo { ///定义一个名称为Demo的接口。      public abstract void show1();      public abstract void show2();  }  //定义子类去覆盖接口中的方法。类与接口之间的关系是 实现。通过 关键字 implements  class DemoImpl implements Demo { //子类实现Demo接口。      //重写接口中的方法。      public void show1(){}      public void show2(){}  }
06 an implementation class or an abstract class
A: 接口的实现类   一个类如果实现类接口,有两种操作方法:   第一:实现类是非抽象类,就需要重写接口中所有的抽象方法.   第二:实现类也声明为抽象类,那么实现类可以不重写接口中的抽象方法。
07 multiple implementations of classes and interfaces
    • A: multiple implementations of interfaces
      Understanding the characteristics of the interface, then think about why to define the interface, the use of abstract class description is no problem, the interface exactly what is the use of it?
      Interface The most important embodiment: to solve the disadvantages of multiple inheritance. This mechanism of multi-inheritance is done in Java through multiple implementations.

    • Benefits of the B-Multi implementation
      • How to solve the disadvantages of multiple inheritance?
      • Cons: When multiple inheritance occurs, when multiple parents have the same functionality, the subclass invocation creates uncertainty.
      • In fact, the core reason is that multiple inheritance of the function in the parent class has a principal, which causes the call runtime to not determine which principal content to run.
      • Why do more implementations work?
      • Because the functionality in the interface has no method body, it is explicit by subclasses.
    • C: Case Demo

        interface Fu2{      void show2();  }  class Zi implements Fu1,Fu2 {    // 多实现。同时实现多个接口。      public void show1(){}      public void show2(){}  }
Class 08 implements multiple interfaces at the same time as inheriting classes
    • A: Implement the interface while inheriting
      • Interfaces and classes can be implemented in relation to each other, as well as learning about the relationships between classes and classes that can be inherited. When a class has inherited a parent class and it needs to extend additional functionality, the interface comes in handy.
      • Subclasses extend functionality by inheriting the parent class, and the functionality that is extended through inheritance is the underlying functionality that subclasses should have. What if subclasses want to continue extending functionality in other classes? This is done by implementing an interface.
      • The presence of interfaces avoids the limitations of single inheritance. The basic functionality of the things defined in the parent class. The extended functionality of the things defined in the interface.
    • B: Code Demo
    •   class Fu {      public void show(){}  }  interface Inter {      pulbic abstract void show1();  }  class Zi extends Fu implements Inter {      public void show1() {      }  }  接口的出现避免了单继承的局限性。父类中定义的事物的基本功能。接口中定义的事物的扩展功能。
09 Multiple Inheritance of interfaces
    • A: Multiple Inheritance of interfaces
      • When learning classes, you know that relationships between classes and classes can be generated through inheritance, between interfaces and classes
      • You can create relationships through implementations, so what is the relationship between interfaces and interfaces.
      • You can use extends to inherit between multiple interfaces.
    • B Code Demo
      Interface fu1{
      void Show ();
      }
      Interface fu2{
      void Show1 ();
      }
      Interface fu3{
      void Show2 ();
      }
      Interface Zi extends fu1,fu2,fu3{
      void Show3 ();
      }

        在开发中如果多个接口中存在相同方法,这时若有个类实现了这些接口,那么就要实现接  口中的方法,由于接口中的方法是抽象方法,子类实现后也不会发生调用的不确定性。
10 Interface Ideas
    • A: The idea of an interface
      • Before learning the code embodiment of the interface, now to learn the idea of the interface, followed by the example of life in the description.
      • For example: We all know that there are many sockets on the computer, and these sockets can be plugged into the appropriate devices, why can they be plugged in?
      • The main reason is that these devices conform to the usage rules of the socket when they are produced, otherwise they will not be able to be plugged into the interface or be unusable. Discover the presence of this socket and let us use more devices.
    • B: Benefits of the interface
      • Summary: interface in the development of its benefits
      • 1, the appearance of the interface expands the function.
      • 2, the interface is actually leaking out of the rules.
      • 3, the appearance of the interface reduces the coupling, that is, the realization of decoupling between equipment and equipment.

      • The appearance of the interface is convenient for later use and maintenance, one side is in the use of the interface (such as computer), a party in the implementation of the interface (plugged in the device). For example: Notebooks Use this rule (interface), computer peripherals implement this rule (interface).

11 The difference between an interface and an abstract class
  • A: What is the difference between an interface and an abstract class when you understand the use of interface ideas and interfaces? Interface in the life embodiment also basic grasp, that in the program interface is how to embody?
    Examples are used to analyze and code to demonstrate the use of abstract classes and interfaces.
  • B: for example:
    • Dog:
      Behavior:
      Roar
      Eat
    • Drug Dog:
      Behavior:
      Roar
      Eat
      Drug
  • C: Thinking:
    • Because the dogs are divided into many kinds, they shout and eat different ways, in the description of the time can not be materialized, that is, shouting and eating behavior can not be clear.
    • When describing the behavior, the behavior of the specific action is not clear, at this point, you can write this behavior as abstract behavior, then this class is abstract class.
    • But when a drug dog has other extra functions, this function is not in the system of this thing. This allows the drug dog to have its own characteristics and other additional functions, which can be defined in an interface.
  • D: Code Demo
  •   interface 缉毒{      public abstract void 缉毒();  }  //定义犬科的这个提醒的共性功能  abstract class 犬科{  public abstract void 吃饭();  public abstract void 吼叫();  }  // 缉毒犬属于犬科一种,让其继承犬科,获取的犬科的特性,  //由于缉毒犬具有缉毒功能,那么它只要实现缉毒接口即可,这样即保证缉毒犬具备犬科的特性,也拥有了缉毒的功能  class 缉毒犬 extends 犬科 implements 缉毒{      public void 缉毒() {      }      void 吃饭() {      }      void 吼叫() {      }  }  class 缉毒猪 implements 缉毒{      public void 缉毒() {      }  }
  • E: Summary of interface and abstract class differences
  •   相同点:      都位于继承的顶端,用于被其他类实现或继承;      都不能直接实例化对象;      都包含抽象方法,其子类都必须覆写这些抽象方法;  区别:      抽象类为部分方法提供实现,避免子类重复实现这些方法,提高代码重用性;接口只能包含抽象方法;      一个类只能继承一个直接父类(可能是抽象类),却可以实现多个接口;(接口弥补了Java的单继承)      抽象类是这个事物中应该具备的你内容, 继承体系是一种 is..a关系      接口是这个事物中的额外内容,继承体系是一种 like..a关系  二者的选用:      优先选用接口,尽量少用抽象类;      需要定义子类的行为,又要为子类提供共性功能时才选用抽象类;
12 Polymorphism Overview
    • A: polymorphic Overview
    • Polymorphism is the third most characteristic of object-oriented after encapsulation and inheritance.

      Real things often reflect a variety of forms, such as students, students are a kind of people, then a specific classmate Zhang San is a student is also a person, that appears two forms.

      Java, as an object-oriented language, can also describe the various forms of a thing. If the student class inherits the person class, a student object is both student and person.

      The polymorphic code in Java is embodied in a subclass object (implementing a Class object) that assigns a reference variable to the subclass (implementing the Class object) and assigns a value to the parent (interface) variable of the subclass (the implementation class object).

      such as the student class can be a subclass of the person class. A student object can either be assigned a reference to a student type, or it can be assigned a reference to a person type.

      The final polymorphic embodiment of the parent class refers to a variable that can point to a child class object.

      The prerequisite for polymorphism is that it is necessary to have a child parent class relationship or a class to implement an interface relationship, otherwise the polymorphism cannot be completed.

      A subclass-overridden method is called when a method is called by a parent class referencing a variable that uses polymorphism.

13 Three formats for polymorphic calls
  • A: polymorphic definition Format:

    • Is that the reference variable of the parent class points to the child class object
    • Parent class type variable name = new subclass type ();
      Variable name. Method name ();
  • B: The format of common polymorphic definitions
  •   父类 变量名 = new 子类();  举例:       class Fu {}      class Zi extends Fu {}      //类的多态使用      Fu f = new Zi();
  • C: Abstract class polymorphic definition Format
  •       抽象类 变量名 = new 抽象类子类();      举例:       abstract class Fu {               public abstract void method();               }      class Zi extends Fu {      public void method(){                    System.out.println(“重写父类抽象方法”);      }      }      //类的多态使用      Fu fu= new Zi();
  • D: Format of the interface polymorphism definition
  •       接口 变量名 = new 接口实现类();      如: interface Fu {                   public abstract void method();      }      class Zi implements Fu {                   public void method(){                    System.out.println(“重写接口抽象方法”);      }      }      //接口的多态使用      Fu fu = new Zi();
  • E: Precautions
    •   同一个父类的方法会被不同的子类重写。在调用方法时,调用的为各个子类重写后的方法。  如 Person p1 = new Student();     Person p2 = new Teacher();     p1.work(); //p1会调用Student类中重写的work方法     p2.work(); //p2会调用Teacher类中重写的work方法  当变量名指向不同的子类对象时,由于每个子类重写父类方法的内容不同,所以会调用不同的方法。
14 Characteristics of polymorphic member methods
  • A: After mastering the basic use of polymorphism, what happens to the members of the class after polymorphism? When we learned inheritance earlier, we knew that the member variables between the child parent classes had their own specific changes,
    • So when polymorphism occurs, does the member variable change in use?
    • Polymorphic occurrences can cause a slight change in the member variables in the child's parent class
  • B: Code Demo
  •   class Fu {      int num = 4;  }  class Zi extends Fu {      int num = 5;  }  class Demo {      public static void main(String[] args)  {          Fu f = new Zi();          System.out.println(f.num);          Zi z = new Zi();          System.out.println(z.num);      }  }
  • C: polymorphic member variables
    • When a member variable of the same name appears in the child parent class, when the variable is called by polymorphic:

      Compile time: Refer to whether the referenced variable belongs to a class that has a called member variable. No, compilation failed.

      Run time: is also a member variable in the class to which the reference variable belongs.

      Simple: Compile and run all refer to the left side of the equals sign. Compile run look to the left.

  • D: polymorphic occurrences can cause a slight change in the member methods in the child parent class. Look at the following code
  •   class Fu {      int num = 4;      void show() {          System.out.println("Fu show num");      }  }  class Zi extends Fu {      int num = 5;      void show() {          System.out.println("Zi show num");      }  }  class Demo {      public static void main(String[] args)  {          Fu f = new Zi();          f.show();      }  }
  • E: Polymorphic Member method
    • Compile time: The reference variable belongs to the class, and if there are no methods called in the class, the compilation fails.

      Run Time: Refer to the class to which the object refers to the reference variable, and run the member method in the class to which the object belongs.

      In short: Compile to look to the left and run to the right.

15instanceof keywords
    • A: Role
      You can use the INSTANCEOF keyword to determine whether an object belongs to a data type. If the student's object belongs to the student class, the student's object also belongs to the human

    • Format:
      Boolean B = Object instanceof data type;

    • Example:
    •   Person p1 = new Student(); // 前提条件,学生类已经继承了人类  boolean flag = p1 instanceof Student; //flag结果为true  boolean flag2 = p2 instanceof Teacher; //flag结果为false
16 Polymorphic-Upward transformation
* A: 多态的转型分为向上转型与向下转型两种:    * B: 向上转型:当有子类对象赋值给一个父类引用时,便是向上转型,多态本身就是向上转型的过程。*     使用格式:    父类类型  变量名 = new 子类类型();    如:Person p = new Student();
17 Polymorphic-Downward transformation
* A: 向下转型:一个已经向上转型的子类对象可以使用强制类型转换的格式,将父类引用转为子* 类引用,这个过程是向下转型。如果是直接创建父类对象,是无法向下转型的!*     使用格式:    子类类型 变量名 = (子类类型) 父类类型的变量;    如:Student stu = (Student) p;  //变量p 实际上指向Student对象    
18 benefits and drawbacks of polymorphism
* A: Benefits and drawbacks of polymorphism * when a reference to a parent class is directed to a subclass object, an upward transformation occurs, that is, the object of the class type is converted to the parent class type.    The benefit of the upward transformation is the hidden subclass type, which increases the extensibility of the code.    * But the upward transformation also has the disadvantage, only uses the parent class common content, but cannot use the subclass characteristic function, the function has the limitation.    * B: Look at the following code//Description animal class, and extract the common Eat method abstract class Animal {abstract void eat (); }//Description Dog class, Inherit animal class, Rewrite Eat method, add Lookhome method class Dog extends Animal {void eat () {System.out.print        ln ("Chew Bones");        } void Lookhome () {System.out.println ("housekeeping"); }}//Description cat class, Inherit animal class, Rewrite Eat method, add Catchmouse method class Cat extends Animal {void eat () {System.out        . println ("Eat fish");        } void Catchmouse () {System.out.println ("catch Mouse"); }} public class Test {public static void main (string[] args) {Animal a = new Dog ();//polymorphic form, Create a Dog object A.eat (); Calling the method in the object will execute the Eat method in the Dog class//A.lookhome ();//Use the Dog class-specific method that requires a downward transformation and cannot be used directly//in order to use the lookhome side of the dog class  Method that requires a downward transition//down transition, a type conversion error may occur, that is, the classcastexception exception          Well, before you go, you need to make a robust judgment if (!a instanceof Dog) {//Determine if the current object is a Dog type System.out.println ("                     Type mismatch, cannot be converted ");             Return } Dog D = (dog) A; Downward transformation d.lookhome ();//Call Dog class Lookhome method}}* C polymorphism Summary: When to use up transformation: When you do not need to face the subclass type, either by increasing extensibility, or by using the work of the parent class        can then be able to complete the corresponding operation, then you can use the upward transformation.            such as: Animal a = new Dog ();    A.eat ();            When to use down transformation when you want to use subclass-specific functionality, you need to use a downward transformation. such as: dog D = (dog) A;            Downward transformation d.lookhome ();//The benefit of the Lookhome method of invoking a dog class: You can use subclass-specific features. The disadvantage is that it is necessary to face a specific subclass object, which is prone to classcastexception type conversion exceptions in the downward transition.        Type judgments must be made before the conversion. such as: if (!a instanceof Dog) {...}
19 polymorphic Examples
 * A: 毕老师和毕姥爷的故事 * 案例:  /*    描述毕老师和毕姥爷,    毕老师拥有讲课和看电影功能    毕姥爷拥有讲课和钓鱼功能  */    class 毕姥爷 {        void 讲课() {            System.out.println("政治");        }            void 钓鱼() {            System.out.println("钓鱼");        }    }        // 毕老师继承了毕姥爷,就有拥有了毕姥爷的讲课和钓鱼的功能,    // 但毕老师和毕姥爷的讲课内容不一样,因此毕老师要覆盖毕姥爷的讲课功能    class 毕老师 extends 毕姥爷 {        void 讲课() {            System.out.println("Java");        }            void 看电影() {            System.out.println("看电影");        }    }        public class Test {        public static void main(String[] args) {            // 多态形式            毕姥爷 a = new 毕老师(); // 向上转型            a.讲课(); // 这里表象是毕姥爷,其实真正讲课的仍然是毕老师,因此调用的也是毕老师的讲课功能            a.钓鱼(); // 这里表象是毕姥爷,但对象其实是毕老师,而毕老师继承了毕姥爷,即毕老师也具有钓鱼功能                // 当要调用毕老师特有的看电影功能时,就必须进行类型转换            毕老师 b = (毕老师) a; // 向下转型            b.看电影();        }    
20 notebook computer Case
    • A: Case Introduction
      • Define the USB interface (with open function, turn off function), notebook to use USB device, that is, the notebook in the production need to reserve the USB interface can be plugged into the USB device, that is, the notebook has the function of using USB device,
      • But specifically what USB devices, notebooks do not care, as long as the devices that meet the USB specifications can. Mouse and keyboard to be able to use on the computer, then the mouse and keyboard must also adhere to the USB specification, or the mouse and keyboard production can not be used
      • Describe notebook class, realize notebook using USB mouse, USB keyboard
        USB interface with open function, off function
        Notebook class, including running function, shutdown function, using USB device function
        Mouse class, to conform to the USB interface
        Keyboard class, to conform to the USB interface
    • B: Case Study
      • Phase One:
        Using notebooks, notebooks have run function, need notebook object to run this function
      • Stage Two:
        Want to use a mouse, there is a function to use the mouse, and more than a mouse object.
      • Phase III:
        Also want to use a keyboard, and one more function and an object
      • Problem: Each function needs to define a method in the notebook object, the discomfort, the program extensibility is very poor.
        Reduce the coupling of peripherals and laptops such as mice and keyboards.
21 Notebook computer Case code implementation
 * A: Code Implementation of the definition of mouse, keyboard, notebook three should abide by the rules interface USB {void open ();//Open function void Close ();//Shutdown function}        The mouse implements the USB rule class Mouse implements USB {public void Open () {System.out.println ("mouse on");        } public void Close () {System.out.println ("mouse off"); }} The keyboard implements the USB rule class KeyBoard implements USB {public void Open () {System.out.println ("        Keyboard Open ");        } public void Close () {System.out.println ("keyboard off"); }} Definition Notebook class NoteBook {//notebook on run function public void run () {System.out.println ("        Notebook Running "); }//notebook using a USB device, when the notebook object calls this feature, it must pass a USB device compliant with USB to public void Useusb (USB USB) {//To determine if there is a U                SB Device if (USB! = null) {Usb.open ();            Usb.close ();       }} public void ShutDown () {System.out.println ("notebook off"); }} public class Test {public static void main (string[] args) {//Create notebook entity object Note            Book NB = new NoteBook ();                Notebook open Nb.run ();            Create mouse entity object Mouse m = new Mouse ();                Notebook using mouse Nb.useusb (m);            Create a keyboard entity object KeyBoard KB = new KeyBoard ();                Notebook using keyboard Nb.useusb (KB);        Notebook off Nb.shutdown (); }    }
Job Testing

1. What is polymorphism and what is the precondition of polymorphism?

2. What are the characteristics of member access in polymorphism?
Member variables
Member method (non-static method)
Static methods

3, what is the interface, what is its characteristic?

4. What are the characteristics of the interface members?

5. What is the difference between an abstract class and an interface?

6: Define a parent class animal Eat method, define the two subclass of the Dog-specific method Keephome, the Cat-specific method catchmouse; and override the Eat method
To write a method in the test class, the parameter list has a parameter Animla type,
Requirement: Call this method to pass the dog object and the Cat object separately, use instanceof to make a call to eat, and their unique method

7. Test: If the return value type of a method is a parent class, can you return a subclass object. (The parent class, whether it is a class, an abstract class, or an interface)

8. There are two kinds of oldphone newphone; Two classes have the call () SendMessage () method (consider extracting a parent class upwards);

    已知接口IPlay中有一个方法 playGame(),NewPhone添加玩游戏的功能;要求: 分别测试OldPhone和NewPhone的两个方法,再测试新手机palyGame()的方法.

9. (Complete the following car case)

描述:汽车都具有跑的功能,普通的奥迪车也不例外,但是高端的奥迪车除了具有跑的功能外,还具有自动泊车和无人驾驶的功能!需求:定义普通奥迪车,高端奥迪车,实现描述中的功能并测试

11_java Object-oriented _ 11th day (interface, polymorphism) _ Handout

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.