Java Learning notes 7--abstract classes and abstract methods

Source: Internet
Author: User
Tags gety

1. Terminating class and terminating method

Classes and methods that are decorated with the final modifier, the terminating class cannot be inherited, and the finalization method cannot be overridden by subclasses of the current class

Characteristics of the terminating class: cannot have derived classes

Reasons for the existence of the terminating class:

Security: One technique that hackers use to disrupt a system is to create a class of derived classes, and then use their classes instead of the original classes

Design: You think your class is the best or conceptually your class should not have any derived classes

Characteristics of the finalization method: cannot be overridden by a derived class

Reasons for the existence of the finalization method:

For some of the more important methods that you do not want the subclass to make changes, you can declare it as an finalization method. Prevents sub-classes from error rewriting of the parent class's key methods, which increases the security and correctness of the code

Improve operational efficiency. Typically, when the Java Runtime environment (such as the Java Interpreter) runs a method, it first finds the method in the current class, then finds it in its superclass, and always looks up at the class level until the method is found

Examples of final methods:

Class parent{public   Parent () {   }//constructor method   final int getpi () {return math.pi;}//Finalization method}

Description: GETPI () is a finalization method declared with the final modifier and cannot be overloaded in subclasses

2. Abstract class

Abstract class: A class that represents an abstract concept

    • A class that does not have a specific instance object and cannot be instantiated using the new method

    • Add modifier to abstract before class

    • Can contain anything that a general class can contain, such as a construction method, a non-abstract method

    • It can also contain abstract methods, which are only declarations of methods, without the implementation of methods

Existence Meaning:
    • Abstract classes are a high-level generalization of class hierarchies, and the role of abstract classes is to allow other classes to inherit its abstract features.

    • An abstract class can include public behavior that is shared by all its subclasses

    • An abstract class can include public properties that are shared by all its subclasses

    • Abstract classes cannot be used as templates to create objects in a program;

    • Force the user to generate more specific instances when the user generates the instance, guaranteeing the security of the Code

As an example:

Abstracts the public properties and methods of all graphs into the abstract class shape. The characteristics of 2D and 3D objects are extracted separately to form two abstract classes of Twodimensionalshape and Threedimensionalshape.

–2d graphics include circles, triangles, rectangles, and squares

–3d graphics include cube, Sphere, or tetrahedron

– In UML, the class name of an abstract class is italicized to distinguish it from a specific class:

The syntax of an abstract class declaration is

Abstract class Number {    ...}
3. Abstract methods

The syntax form for a declaration is:

Public abstract <returnType> <methodName> (...);

There are only method headers, and there are no method bodies and operation implementations, and the implementation is done by different subclasses of the current class in their respective class declarations, and abstract classes can contain abstract methods

Issues to be aware of:

    • If a subclass of an abstract class is not an abstract class, it must write the method body for all abstract methods in the parent class, that is, overriding all abstract methods in the parent class

    • Only abstract classes can have an abstract method, that is, if a class contains abstract methods, you must declare the class as an abstract class

    • In addition to abstract methods, abstract classes can also include non-abstract methods

Advantages of abstract methods:

    • Hide specific details, all subclasses use the same method header, which contains all the information you need to know when calling the method

    • Forcing a subclass to complete a specified behavior, specifying the "standard" behavior that its subclasses need to use

Give an example of a drawing:

Various graphs need to implement a drawing method, which declares a draw abstract method in their abstract parent class.

Abstract class Graphicobject {    int x, y;    void MoveTo (int newx, int newy) {...}    abstract void Draw ();}

Then rewrite the draw method in each of the subclasses, for example:

Class Circle extends Graphicobject {    void Draw () {  ...  }} Class Rectangle extends Graphicobject {    void Draw () {  ...  }}

To give an example:

First define an abstract class:

Abstract class Person {    private String name;   Concrete Data Public person    (String N) {  //constructor        name = N;    }    Public String GetName () {  //specific method        return name;    }    Public abstract String getdescription (); Abstract method}

The following extends a specific subclass student by an abstract class person:

Class Student extends person {    private String major;    Public Student (string n, String m) {        super (n);        Major = M;    }    Public String getdescription () {  //implement GetDescription method in abstract class        return "a student majoring in" + Major;    }}

Extend a specific subclass of employee by abstract class Person:

Class Employee extends person {    private double salary;    Private Date Hireday;    Public Employee (String N, double S, int year, int month, Int. day) {        super (n);        Salary = s;        GregorianCalendar calendar = new GregorianCalendar (year, month-1, day);        Hireday = Calendar.gettime ();    }    Public double getsalary () {        return salary;    }    Public Date getDate () {        return hireday;    }    Public String getdescription () {  //implements GetDescription method in abstract class        return String.Format ("an employee with a salary of $%.2f ", salary);    }    public void Raisesalary (double bypercent) {        Double raise = salary * BYPERCENT/100;        Salary + = Raise;    }}

The test procedure is as follows:

public class Javatest {public    static void Main (string[] args) {        person[] people = new person[2];        People[0] = new Employee ("Hary Hacker", 50000, 1989, 1);        PEOPLE[1] = new Student ("Maria Morris", "Computer Science");        for (person P:people)            System.out.println (p.getname () + "," + p.getdescription ());}    }

The results of the operation are as follows:

Hary Hacker, an employee with a salary of $50000.00
Maria Morris, a student majoring in computer

3. Combinations of classes

An important idea of object-oriented programming is to use software objects to imitate real-world objects, in the real world, most objects are made up of smaller objects.

Like real-world objects, objects in software are often made up of smaller objects, and Java classes can have objects of other classes as members, which is a combination of classes

The syntax of the composition is simple, as long as the object of the existing class is placed in the new class, you can use the "has a" statement to describe the relationship

For example, consider the kitchen class to provide cooking and refrigerated food functions, it is natural to say "My kitchen ' has a ' cooker/refrigerator". Therefore, it is easy to put objects Mycooker and Myrefrigerator in class kitchen. The format is as follows:

Class cooker{   //classes of statements  }class refrigerator{   //class statements}class kitchen{cooker mycooker       ;        Refrigerator Myrefrigerator;}

A line segment consists of two endpoints:

public class   Point//DOT class {     private int x, y;  Coordinate public point     (int x, int y) {this.x = x; this.y = y;}     public int GetX ()  {  return x;}     public int GetY ()  {  return y;}} Class   Line//Segment classes {   private point  p1,p2;     Both ends   of line (point A, dot b) {        P1 = new points (A.getx (), a.gety ());      P2 = new Point (B.getx (), b.gety ());   }   Public double Length () {        return math.sqrt (Math.pow (p2). GetX ()-p1. GetX (), 2) + Math.pow (p2. GetY ()-p1. GetY (), 2));}   }

Comparison of combinations with inheritance:

The "include" relationship is expressed by a combination.

If you want to take advantage of the attributes of an existing class inside a new class and do not want to use its interface, you should usually choose a combination, we need to embed the private object of the existing class in the new class

If you want the class user to access the composition of the new class directly, you need to make the member object's properties public

The "belongs" relationship is expressed by inheritance

Get a ready-made class and make a special version of it. Typically, this means that we are ready to use a general-purpose class and tailor it to specific needs

As an example:

Car object is a good example, because the assembly of the car is a factor to be considered in the fault analysis, so it helps the client programmer understand how to use the class, and the class creator's programming complexity will be greatly reduced

Class Engine {//  engine class public void    start () {} public    void Rev. () {} public    void Stop () {}}class Wheel {//Wheel  class public      void Inflate (int psi) {}}class window {//window class public    void Rollup () {} public    void Rolldown () {}}class Door {//Vehicle Category Public    window window = new window ();    public void Open () {} publicly    void Close () {}}public class Car {public    engine engine = new engine ();    Public wheel[] Wheel = new Wheel[4];    Public Door left = new Door (), right = new Door (); Public Car () {for        (int i = 0; i < 4; i++)            wheel[i] = new Wheel ();    }    public static void Main (string[] args) {        car car = new car ();        Car.left.window.rollup ();        Car.wheel[0].inflate (*);    }}

Many times it is required to combine combinations with inheritance to create a more complex class

For example (combination and inheritance examples):

Class Plate {//Declaration plate Public Plate (int i) {System.out.println ("Plate constructor");        }}class Dinnerplate extends Plate {//Declaration plate as sub-class public dinnerplate (int i) {super (i);    System.out.println ("Dinnerplate constructor");    }}class utensil {//Declaration apparatus utensil (int i) {System.out.println ("utensil constructor");        }}class Spoon extends Utensil {//Declare the spoon as the child of the appliance public Spoon (int i) {super (i);    System.out.println ("Spoon constructor");        }}class Fork extends Utensil {//Declare fork as the sub-class public fork of the appliance (int i) {super (i);    System.out.println ("Fork constructor");        }}class Knife extends Utensil {//Declare the meal knife as the subclass of the appliance public Knife (int i) {super (i);    System.out.println ("knife constructor"); }}class Custom {//Declare the customary public custom (int i) {System.out.println ("custom constructor") to do something;}} public class Placesetting extends Custom {//Declare the layout of the table Spoon SP; Fork FRK;     Knife kn;    Dinnerplate PL;    Public placesetting (int i) {    Super (i + 1);        SP = new Spoon (i + 2);        FRK = new Fork (i + 3);        kn = new Knife (i + 4);        PL = new Dinnerplate (i + 5);    System.out.println ("Placesetting constructor");    } public static void Main (string[] args) {placesetting x = new placesetting (9);  }}

Operation Result:

Custom Constructor

Utensil constructor

Spoon Constructor

Utensil constructor

Fork Constructor

Utensil constructor

Knife constructor

Plate Constructor

Dinnerplate Constructor

Placesetting Constructor

Java Learning notes 7--abstract classes and abstract methods

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.