Java study notes 7 -- abstract classes and abstract methods, java study notes 7 -- Abstract

Source: Internet
Author: User

Java study notes 7 -- abstract classes and abstract methods, java study notes 7 -- Abstract

Next, we learned the following:

Java study Note 6-class inheritance, Object class

Java study notes 5-Class Method

Java Study Notes 4-basic concepts of classes and objects (2)

Java Study Notes 3-basic concepts of classes and objects (1)

Java study Note 2 -- data type, array

Java study Note 1-Summary of the development environment Platform

URL: http://www.cnblogs.com/archimedes/p/java-study-note7.html.

1. Termination class and termination method

For classes and Methods Modified by the final modifier, the final class cannot be inherited, and the final method cannot be overwritten by the subclass of the current class.

Terminator class features: a derived class is not allowed.

Reasons for the existence of the end class:

Security: one method that hackers use to disrupt the system is to create a class derived class, and then use their class to replace the original class.

DESIGN: You think your class is the best or your class should not have any Derived classes in terms of concept

Terminator features: cannot be overwritten by a derived class

Reasons for the existence of the termination method:

Methods that are important and do not require subclass changes can be declared as termination methods. This prevents the subclass from overwriting the key methods of the parent class, increasing the code security and correctness.

Improve operation efficiency. Generally, when a java Runtime Environment (such as a java interpreter) runs a method, it first searches for the method in the current class, and then searches for the method in its superclass, and keep searching along the class level until the method is found.

Final method example:

Class Parent {public Parent () {}// constructor final int getPI () {return Math. PI ;}// Terminator}

Note: getPI () is the final method declared with the final modifier and cannot be overloaded in the subclass.

2. abstract class

Abstract class: a class that represents an abstract concept.

  • Classes without specific instance objects cannot be instantiated using the new method

  • The modifier abstract must be added before the class.

  • It can contain anything that a common class can contain, such as constructor and non-abstract methods.

  • It can also contain abstract methods. This method only has the declaration of methods, and there is no implementation of methods.

Meaning:
  • An abstract class is a high-level generalization of the class hierarchy. The role of an abstract class is to let other classes inherit its abstract features.

  • Abstract classes can include public behaviors shared by all its subclasses.

  • An abstract class can include public attributes shared by all its subclasses.

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

  • Forces users to generate more specific instances when users generate instances to ensure code security.

For example:

Abstract The common attributes and methods of all images to the abstract class Shape. Then, the features of 2D and 3D objects are extracted to form two abstract classes: TwoDimensionalShape and ThreeDimensionalShape.

-2D graphics include Circles, Triangles, Rectangles, and Squares

-3D images include Cube, Sphere, or Tetrahedron

-In UML, the Class Name of the abstract class is italic, which is different from the specific class:

 

The syntax of the abstract class declaration is

abstract class Number {    . . .}
3. Abstract METHODS

The statement syntax is as follows:

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

There is only a method header, but no method body and operation implementation. The specific implementation is completed by different subclasses of the current class in their respective class declarations. abstract classes can contain abstract methods.

Notes:

  • 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, rewrite all abstract methods in the parent class.

  • Only abstract classes can have abstract methods. That is, if a class contains abstract methods, the class must be declared as an abstract class.

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

Advantages of abstract methods:

  • Hide detailed information. All sub-classes use the same method header, which contains all the information to be understood when calling this method.

  • Forces a subclass to complete the specified behavior and specifies the "standard" behavior required by its subclass.

An example of drawing:

Various graphics require drawing methods. You can declare 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 subclass, for example:

class Circle extends GraphicObject {    void draw() {  . . .  }}class Rectangle extends GraphicObject {    void draw() {  . . .  }}

For example:

First, define an abstract class:

Abstract class Person {private String name; // specific 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 of Student through the abstract class Person:

Class Student extends Person {private String major; public Student (String n, String m) {super (n); major = m;} public String getDescription () {// implement the getDescription method return "a student majoring in" + major;} in the abstract class ;}}

Extends a specific subclass of Employee by using the 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 () {// implement the getDescription method return String in the abstract class. 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, 10, 1);        people[1] = new Student("Maria Morris", "Computer science");        for(Person p : people)            System.out.println(p.getName() + ", " + p.getDescription());    }}

The running result is as follows:

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

3. Combination of Classes

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

Similar to objects in the real world, objects in software are often composed of smaller objects. Java classes can contain objects of other classes as members. This is a combination of classes.

The syntax of the combination is very simple. You only need to put the existing class objects into the new class. You can use the "has a" statement to describe the relationship.

For example, considering that the Kitchen class provides cooking and refrigerating functions, it is natural to say "my kitchen 'has a' cooker/refrigerator ". Therefore, you can simply put the objects myCooker and myRefrigerator in the Kitchen class. The format is as follows:

Class Cooker {// class statement} class Refrigerator {// class statement} class Kitchen {Cooker myCooker; Refrigerator myRefrigerator ;}

A line segment contains two endpoints:

Public class Point // Point 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 // Line segment class {private Point p1, p2; // Line (Point a, Point B) {p1 = new Point (. getX (),. 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 between combination and inheritance:

The "include" link is expressed in combination.

If you want to use the features of an existing class in the new class instead of using its interfaces, you should usually select a combination. We need to embed the private object of the existing class in the new class.

L if you want the class user to directly access the composition of the new class, you must change the attribute of the member object to public.

The "belonging" relationship is expressed by inheritance.

Get a ready-made class and make a special version of it. Normally, this means that we are going to use a class for general purposes and customize it according to specific needs.

For example:

Car (automobile) objects are a good example. Because automobile assembly is a factor to be considered during fault analysis, it helps the customer programmers understand how to use the class, in addition, the programming complexity of class creators 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 {// Door class public Window window Window = new Window (); public void open () {} public 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 (72 );}}

In many cases, it is required to combine the combination and inheritance technologies to create a more complex class.

For example, combination and inheritance ):

Class Plate {// declare Plate public Plate (int I) {System. out. println ("Plate constructor") ;}} class DinnerPlate extends Plate {// declare the Plate as the subclass public DinnerPlate (int I) {super (I); System. out. println ("DinnerPlate constructor");} class Utensil {// declare the appliance Utensil (int I) {System. out. println ("Utensil constructor");} class Spoon extends Utensil {// declare that the Spoon is a subclass of the appliance public Spoon (int I) {super (I); System. out. println ("Spoon constructor");} class Fork extends Utensil {// declare the sub-class public Fork (int I) {super (I); System. out. println ("Fork constructor");} class Knife extends Utensil {// declare the Knife as a subclass of the appliance public Knife (int I) {super (I); System. out. println ("Knife constructor");} class Custom {// declare the habit of doing something public Custom (int I) {System. out. println ("Custom constructor") ;}} public class PlaceSetting extends Custom {// declare the layout of the dining 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 );}}

Running result:

Custom constructor

Utensil constructor

Spoon constructor

Utensil constructor

Fork constructor

Utensil constructor

Knife constructor

Plate constructor

DinnerPlate constructor

PlaceSetting constructor

References:

Java programming-Tsinghua University

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.