Java starts from scratch and the basics of learning notes & lt; abstract class _ interface _ polymorphism & gt; (13)

Source: Internet
Author: User

Abstract class _ interface _ polymorphism Abstract keywords indicate Abstract classes. They can modify a class or method. If it is used to modify a class, this class is an abstract class. If it is used to modify a method, this method is an abstract method. abstract class: syntax format: access modifier + abstract + class name {abstract method; common method} example: package com. ibm. abstractes; public abstract class AbstractesDemo {} the abstract class cannot be instantiated. That is to say, the abstract class cannot be created by the new Keyword. Its object abstract method is a method modified by using the distinct, method does not have method body syntax format access modifier + response at + return value type method name (parameter list); public abstract class AbstractDemo {public abstract String show (); public abstract int show1 (int m, Int n);} the abstract method only has the life of the method, and there is no specific implementation of the method. Abstract classes can contain both abstract and common methods. If there is no abstract method in the abstract class, the abstract class does not exist. When any condition is met, the class must be defined as an abstract class: 1 this class contains one or more abstract methods. 2 classes inherit the abstract methods in the parent class, at least one abstract method is not implemented. * abstract classes can be inherited. If a common class inherits an abstract class, it is necessary to implement all abstract methods in abstract classes * If a class inherits an abstract class and is not inherited from all abstract methods of the class, this class must be an abstract class, an abstract class can inherit another abstract class or multi-level inheritance, but an abstract class can only inherit one abstract class. Class 3 implements an interface, but not all methods in the interface * methods in the interface are all Abstract METHODS * if a common class implements an interface, all methods in the interface need to be implemented, if not all methods in the interface are implemented, this class must be an abstract class and cannot be directly instantiated. If you need to instantiate an object, then, the parent class Object = new subclass Constructor () must be instantiated through the like. The algorithm used to calculate the fare for buying a bus ticket, train ticket, or plane ticket: Bus fare: Fare + fire insurance Ticket: Fare (for students/2 adults) + plane insurance Ticket: Fare + package com. ibm. abstrates; public abstract class SaleTicket {/*** @ param money fare * @ param save insurance * @ return */public abstract float saleCar (float money, float save ); public abstract float saleTrain (float money, String typeP, float save); public abstract float saleFly (float money, float otherMoney, float otherMoney1, float save);} package com. ibm. abstrates; public clas S SaleClient extends SaleTicket {public float saleCar (float money, float save) {// TODO Auto-generated method stub return money + save;} @ Override public float saleTrain (float money, string typeP, float save) {float f = 0.0f; if (typeP. equals ("adult") {f = money + save;} if (typeP. equals ("kids") {f = money/2 + save;} return f ;}@ Override public float saleFly (float money, float otherMoney, float otherMoney 1, float save) {return money + otherMoney + otherMoney1 + save;} package com. ibm. extends ates; public class SaleTest {public static void main (String [] args) {// The abstract class cannot be instantiated // SaleTicketst = new SaleTicket (); SaleClient SC = new SaleClient (); system. out. println (SC. saleCar (36, 1); // The abstract class has only the life of the method, and there is no specific implementation, the specific implementation method is implemented in its subclass // SaleTicket st = new SaleClient (); // The subclass object is assigned to the reference of the parent class, when calling method execution, the method SaleTicket st in the subclass is null; SaleClient sc1 = new SaleClient (); st = sc1; System. out. println (st. saleCar ();} an abstract class can inherit from another abstract class, so the methods in the abstract class will be inherited and can assign the object of a subclass to the reference of the parent class, the object calling method of the parent class points to the abstract method in the class, But executes the subclass method. Pattern Design Pattern: the skeleton of an algorithm defined in the parent class. The implementation details of an algorithm are embodied in its sub-classes, but not specific implementation algorithms. The method defined in the parent class is an abstract method. In its subclass, the implementation method is a common method v. For example, when a bank calculates interest, the interest rate is multiplied by the principal and deposit time, however, different deposit methods have different interest rate calculation methods. Therefore, in the related methods of the account class, only the algorithm skeleton is set up, but not specific. The specific implementation is completed by sub-classes. Abstract class LoanAccount {// Interest, Principal private double interest, Fund; public double calculateInterest () {// calculate the Interest rate double interest = getInterestRate (); // algorithm used to calculate the Interest: the principal * Interest rate, // but the Interest rate algorithm does not implement Interest = getFund () * getInterestRate (); return Interest;} in this class ;} /** different deposit types have different interest rates. Therefore, the interest rate calculation method is not implemented in this parent class, instead, it is postponed to the subclass to implement the */protected abstract double getInterestRate () ;}} interface: a set of abstract methods and constants. That is to say, the interface can only have Abstract methods and constants, and cannot have other common methods except abstract methods. An interface can be seen as a class that is more abstract than an abstract class. There is only method life in the interface, and there is no specific method implementation. The interface only contains constants or abstract methods. syntax format of the interface: access modifier + interface Name {// constant: access modifier + static + final + Data Type + constant name = constant value note: java coding specification, constant names must all be capitalized // abstract method} * @ authorAdministrator * the interface is a more abstract class than the abstract class * abstract class can have abstract methods and common methods, while the interface can only have Abstract METHODS * interface can only contain constants, there cannot be a variable * a class uses the implements keyword to implement an interface, * All methods not implemented in the implementation interface * The interface can look at multiple sets of unimplemented Methods * Can a class implement multiple interfaces? * A class can implement multiple interfaces. * but this class must implement all unimplemented methods in multiple interfaces. * Can an interface inherit one interface? * An interface can inherit one or more interfaces. Multiple Interfaces are inherited. * multiple interfaces are inherited using the extends keyword. "," is used between interfaces to separate package com. ibm. interfaces; public interface InterfaceDemo {// you can define constants in the interface, but cannot define variables. // you can only have abstract methods in the interface, but not public static final StringNAME = "Ibm "; public abstract void show (); // Stringstr; // cannot be defined // public void show2 () {}// cannot be defined} an interface can inherit another interface, the inherited keywords are also extends, and different from the class: an interface can inherit multiple interfaces. If an interface inherits multiple interfaces, It inherits all the methods in the interface. If a class implements this interface, this class should implement all methods in all interfaces. One class implements multiple interfaces using the implements keyword to implement multiple interfaces. The interfaces and interfaces are directly used ", if a class implements one or more interfaces, the class must implement any methods in the interface. Public class name implements Interface Name 1, interface name 2, interface Name 3 {} multiple classes can implement one interface at a time. One class can implement one or more interfaces at a time. If one class implements multiple interfaces at a time, this class should overwrite the abstract methods in all interfaces. Package com. ibm. interfaces; public class Client implements FatherInterface, GrandFatherInterface {@ Override public void makeMoney () {// TODO Auto-generated method stub} @ Override public String getName () {// TODO Auto-generated method stub return null;} @ Override public void show () {// TODO Auto-generated method stub} Why should I use the interface? 1. Hiding implementation details of specific methods 2. Improving program scalability 3. Convenient code maintenance polymorphism. Multiple forms of representation. In Java, object variables are polymorphism. A variable of the Aclass type can point both to an object of the Aclass type and to an object of any subclass of Aclass v to transmit parameters in the form of polymorphism, the flexibility of parameter types is enhanced. v. Only one object can have one exact data type. v. If a referenced type variable is declared as the parent class, but actually it references a subclass object, then, this variable cannot access the attributes and methods added to the subclass in the inheritance of classes and classes. If it is passed as an object of the parent class, only methods in the parent class can be accessed. The newly added methods in the subclass cannot access the object that assigns the specific implementation class to the declared interface, the object through the interface points to the abstract method in the interface, but essentially calls the method package com that implements the interface in the implementation class. ibm. polymorphisms; public interface Person {public abstract void run (); public abstract void eat (); public abstract void sleep ();} package com. ibm. polymorphisms; public class Girl implements Person {@ Override public void run () {// TODO Auto-generated method stub System. out. println ("I'm the run method of girl") ;}} package com. ibm. polymorphisms; public class Boy implements Person {@ Override public void run () {// TODO Auto-generated method stub System. out. println ("I am the run method of boy") ;}} package com. ibm. polymorphisms; public class Test {// there is a method to print out the corresponding method of an object // public void show (Girl g) {// g. run (); //} // public void show (Boy B) {// B. run (); //} // public void show (Man m) {// m. run (); //} public void show (Person p) {p. run ();} public static void main (String [] args) {new Test (). show (new Girl (); new Test (). show (new Boy (); new Test (). show (new Man () ;}} Object Modeling (casting) the so-called object modeling is the mutual conversion between objects, but there must be a relationship between objects. Object Modeling is classified into two categories: package com. ibm. casting; public class Father {} package com. ibm. casting; public class Son extends Father {} automatic styling: from small to large, from subclass to parent class // automatic styling is also implicitly converted // the shape of the object is the mutual conversion of the object, here is the mutual conversion between the Father and Son classes // automatic styling converts the subclass object to the parent class // Father f = new Son (); // System. out. println (f); force shape: from large to small, the parent class rotor class // forcibly converts the parent class object to a subclass. // If You Want To forcibly convert the parent class object to a subclass object, then you must first convert the subclass object to the parent class Object // then convert the converted parent class object to a subclass object // If you directly convert the parent class to a subclass object, father f = new Son (); Son s = (Son) f; System. out. println (s); instanceof // The instanceof keyword is used to determine whether the created object is an object of a certain class. // 1. convert the subclass object to the parent class object through implicit conversion. The converted object // Father f = new Son (); // Father f = null; // Son s = new Son (); // f = s; // System. out. println (f instanceof Father); // System. out. println (f instanceof Son); // Son s1 = (Son) f; // System. out. println (s1 instanceof Son); // System. out. println (s1 instanceof Father );

Related Article

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.