catalogue
1.3 implementation steps of polymorphism
1.4 definition of polymorphism
3.2 definition and use of interface
1, Specific contents
Process oriented programming: focus on function realization
Object oriented programming: pay attention to calling!
Three characteristics of object-oriented: encapsulation, inheritance and polymorphism
java object-oriented features: encapsulation, inheritance, polymorphism, abstraction, interface
1.1 concept of polymorphism
An object has many forms
1.2 polymorphic requirements
For a zoo, there is a keeper feed() method, which needs to feed dogs. Dogs have eat() method, and then cats. Cats also have eat() method, and other animals may be fed later. Each animal needs to be added separately
Animal
public class Animal { // How to eat public void eat(){ System.out.println("Eat something"); } }
Cat
public class Cat extends Animal{ @Override public void eat() { System.out.println("The cat is eating"); } }
Dog
public class Dog extends Animal{ @Override public void eat() { System.out.println("The dog is eating"); } }
Feeder
public class Feeder { public void feed(Dog dog){ System.out.println("The keeper is feeding the dog"); dog.eat();// The dog is eating } public void feed(Cat cat){ System.out.println("The keeper is feeding the cat"); cat.eat(); } }
Test
public class Test { public static void main(String[] args) { // The keeper feeds dog Feeder feeder = new Feeder(); Dog dog = new Dog(); feeder.feed(dog); //Breeders feed cat Cat cat= new Cat(); cat.eat(); } }
If the zoo keeps adding animals, every animal needs to be added in this way, which is very troublesome
But using polymorphism can solve this problem:
public class Feeder { //If the parameter is a cat, then the parameter is a cat, //If the parameter is a dog, then the parameter is a dog. What is the parameter? At this time, animal is what //And calls the method of the subclass, public void feed(Animal animal){ animal.eat(); } } Corresponding Test Animal yingwu =new YingWu();//It is allowed to assign a subclass type to a parent type //If a subclass object is assigned to a parent object, the parent object will run using the characteristics of the subclass object when it runs //Method of parent class pointing to child class yingwu.eat();
1.3 implementation steps of polymorphism
1) Create parent Animal method eat ()
2) Create Cat Dog Pig subclass of Animal and override eat()
3) Create a method feed (Animal Animal Animal) for the breeder to feed animals
4) Create a keeper object create an animal object feed (specific animal) in the keeper object
1.4 definition of polymorphism
Polymorphism literally means "multiple states". stay Object oriented language In, many different implementations of interfaces are polymorphic. Refer to Charlie Calverts' description of polymorphism - polymorphism allows you to set the parent object to one or more of his Sub object After assignment, the parent object can operate in different ways according to the characteristics of the child object currently assigned to it. Simply put, it is a sentence: it is allowed to assign a subclass type to a parent class type, and the parent class refers to the subclass object. At this time, the parent class points to the memory address of the child class.
The premise of polymorphism is inheritance and method rewriting
Upward Transformation: class I refers to class I object (it is automatically generated, but the disadvantage is that it loses the ability to adjust the unique method of class I)
Downward Transformation: the class refers to the class object (forced conversion), and the methods and properties in the subclass object can be called at this time. The disadvantage is that it is easy to cause type conversion errors
//Upward transformation * * * class introduction class objects (automatically generated, but with the disadvantage of losing the ability to adjust the unique method of class) Animal dog1=new Dog();//Upward transformation * * * at this time, dog is an Animal type and an object of the parent class //Downward transformation * * * class refers to a subclass object (forced conversion), and methods and properties in subclass objects can be called at this time. The disadvantage is that it is easy to cause type conversion errors Dog dog2=(Dog)dog1;//Downward transformation * * * convert the dog object of Animal into an object of dog class dog2.watchDoor();//The object of dog class can call all the methods of dog
Type conversion exception occurs during downward transformation
/* Cat cat =(Cat) dog1;//Is a sibling subclass ClassCastException:Type conversion exception Exception in thread "main" java.lang.ClassCastException: com.aaa.exer.Dog cannot be cast to com.aaa.exer.Cat at com.aaa.exer.Test.main(Test.java:34) This error occurs when dog1 pointing to the Dog class is forcibly converted to an object cat of the same cat class */ /* Animal animal =new Animal(); Dog dog3=(Dog)animal; At this time, the object animal pointing to the animal class is forcibly converted to dog3 of the Dog class, and an error will also be reported ClassCastException:Type conversion exception Exception in thread "main" java.lang.ClassCastException: com.aaa.exer.Dog cannot be cast to com.aaa.exer.Cat at com.aaa.exer.Test.main(Test.java:34) */
2, abstract class
reflection:
1) Can the keeper feed Animal?
No: because animal is just a parent class abstracted by us, in order to better solve the code problem. Animal is not an actual object. But people can feed a specific animal.
2) Can Animal eat?
Yes: I can eat, but I only have the behavior of eating.
All animals have the behavior of eating, but we must be specific to a certain animal before we can say what this animal eats.
3) Is it OK not to write eat() in Animal?
may not. Because the eat() of the subclass inherits and overrides the eat() method of the parent class, it cannot pass without writing and compiling. Because the premise of polymorphism is inheritance and method rewriting.
4) Is it OK not to write eat() in dog, cat and pig?
sure. The syntax will not report an error, but what the runtime will execute is the eat() method of the parent class, which is meaningless at this time.
2.1 abstract concepts
Abstract is the process of extracting common and essential features from many things and discarding their non essential features.
That is to say, the abstract parent class only has the concept of corresponding behavior, and the specific behavior is only available in each specific subclass.
2.2 abstract method
public abstract class Animal { //Abstract abstract abstract keyword //Methods in abstract classes must be public and cannot be private public void eat(){ System.out.println("This is an animal. All animals eat"); } //[permission modifier] abstract return value method name()// No method body {} public abstract void aaa(); //Abstract: the modified class is an abstract class, and the modified method is an abstract method //A class containing abstract methods must be abstract //Abstract classes do not necessarily have abstract methods //Abstract classes can have ordinary methods //Abstract classes are inherited by subclasses, //After the subclass inherits the abstract class, it must override the abstract method in the parent class. If the subclass does not want to override the method of the parent class, it needs to turn the subclass into an abstract class //Abstract classes have constructors, but they cannot be new }
3, Interface
3.1 concept of interface
Interface: in the JAVA programming language, it is an abstract type and a collection of abstract methods. The interface is usually declared as interface. An interface has only the characteristics of methods but no implementation of methods. Therefore, these methods can be implemented by different classes in different places, and these implementations can have different behaviors (functions).
1, Java interface, the structure existing in the Java language, has specific syntax and structure;
2, The feature set of methods of a class: java interface
Logical abstraction: Interface
You can first treat the interface as a special abstract class
3.2 definition and use of interface
Format of interface definition
[permission modifier] interface interface name {}
Interface usage steps
1. The methods in the interface cannot be used directly. There must be an implementation class to implement the interface
[Permission modifier] class Class name implements Interface 1,Interface 2,Interface 3{} //Multiple interfaces can be implemented at the same time public class Mouse implements USB{}
2. The implementation class of the interface must (override and rewrite) implement all abstract methods in the interface
Note: if the implementation class does not override the method in the interface, it needs to be changed into an abstract class
3. Create an object that implements the class and call the method.
Interfaces must be named in uppercase I At the beginning, it is used to indicate that this is an interface public interface IUsb { public static final double PI=3.14; void write(); } //Implementation class public class Upan implements IUsb{ @Override public void write() { } //Interface needs to implement: Implement //Format: public class class name implements interface //To implement an interface, a class must implement all the methods in the interface }
3.3 contents of interface
Contents that can be included in the interface: member constants, abstract (static) methods, and default methods
Constants are immutable;
public interface IUsb { //Interface is decorated with interface //constant public static final double PI=3.14; //The default must be public static final //If you want to access, you must use static to let other classes call, so you need to use public to modify it //Abstract method void write(); //The method in the interface is an abstract method. It has only a method name and no method body //The abstract method in the interface must be two fixed keywords to modify public abstract. These two keywords can be omitted without writing //Default method (new content after jdk1.8) //The default method in the interface is called through the object instead of the implemented method of the implemented class. //Why should there be a default method? Default enhances the general ability of the interface. //Default return value method name() {} / / the default method has a method body //Static method public static void aaa(){ System.out.println("This is a static method"); } //There is no constructor in the interface, and it cannot be new } //The use of constants directly uses the interface name. Constant name public class Test { public static void main(String[] args) { double pi = IUsb.PI; } }
case
public interface Usb { //The constants of the interface are decorated by public static final by default //public static final may not be written. The default is: public static final int AEG=5; //Abstract methods in the interface are decorated by public abstract by default public abstract void work(); void read(); //Default method: //The default decorated implementation class can be rewritten or not default void write(){ System.out.println("This is the default method called"); } //Static method //Static methods cannot be overridden in the implementation class, but can be called through the interface name. Method name public static void aaa(){ System.out.println("This is a static method"); } }
public interface Usb3 { void look(); void see(); }
public class Mouse implements Usb { @Override public void work() { System.out.println("The mouse is working"); } @Override public void read() { System.out.println("The mouse starts reading"); } }
public class Upan implements Usb{ @Override public void work() { System.out.println("U The disk is inserted"); } @Override public void read() { System.out.println("U Disk read"); } }
public class FengShan implements Usb,Usb3{ @Override public void work() { } @Override public void read() { } //The implementation class overrides the default method in the Usb interface @Override public void write() { System.out.println("The fan starts to rotate"); } @Override public void look() { System.out.println("USB3 Called"); } @Override public void see() { } }
Test class:
public class Test { public static void main(String[] args) { //Interface + polymorphism //Interface points to the object that implements the class Usb mouse = new Mouse(); Usb.aaa();//Can only be called by interface name. Static method name mouse.read();//Call overriding method of subclass Mouse mouse.write();//Call the method of the parent class Usb System.out.println(Usb.AEG);//Constants in the interface can be called directly //Polymorphic USBs can become mouse or upan Usb upan = new Upan(); upan.work();//Call overriding method of subclass Upan upan.read();//Call overriding method of subclass Upan Usb fengshan = new FengShan(); fengshan.write();//Overriding the default method of the interface Usb3 fengshan1=new FengShan(); fengshan1.look();//Call the look() method of another interface } }
matters needing attention:
Single inheritance between classes
Classes and interfaces are multi implemented: a class can implement multiple interfaces (the abstract methods in all implemented interfaces should be implemented), which is convenient for later maintenance (modification and extension)
Interfaces and interfaces are multi inherited: if an interface A extends interface B and interface C, interface A can have all the functions of interfaces B and C at the same time, and can also have its own methods.
Interface has no constructor.
Interface polymorphism: a USB interface can show the shape of mouse, keyboard and USB disk
What is the difference between an interface and an abstract class? (question)
abstract class | Interface | |
---|---|---|
Construction method | There is a construction method, but it cannot be new | There is no construction method, and it cannot be new |
inherit | Single inheritance, only one abstract parent class can be inherited, but multi-level inheritance is allowed | An interface can inherit multiple interfaces, and a class can implement multiple interfaces |
Abstract method | Abstract methods should be decorated with public abstract and cannot be omitted. Only the method name and no method body are available | Abstract methods are decorated with public abstract by default and can be omitted. Only the method name and no method body are available |
Abstract method | There can be no abstract methods in an abstract class. The class with abstract methods must be an abstract class | If the interface is not an abstract method, the default method is decorated with default |
constant | Constant names should be capitalized | Constants in the interface are decorated with public static final. Public static final may not be written |