Java Basics (ix): abstract classes

Source: Internet
Author: User

In object-oriented concepts, all objects are depicted by classes, but conversely, not all classes are used to depict objects, and if a class does not contain enough information to depict a specific object, such a class is an abstract class.

Abstract classes In addition to the object cannot be instantiated, other functions of the class still exist, member variables, member methods and construction methods are accessed in the same way as the normal class.

Because an abstract class cannot instantiate an object, an abstract class must be inherited in order to be used. For this reason, it is often decided at the design stage to not design abstract classes.

The parent class contains a common method for the collection of subclasses, but because the parent class itself is abstract, these methods cannot be used.

In Java, an abstract class represents an inheritance relationship in which a class can inherit only one abstract class, while a class may implement multiple interfaces.

First, abstract class:

Abstract classes are used in the Java language to define abstractions. The following example:

 Public Abstract classemployee{PrivateString name; PrivateString address; Private intNumber ;  PublicEmployee (string name, address string,intNumber ) {System. out. println ("Constructing an Employee");  This. Name =name;  This. Address =address;  This. Number =Number ; }    Public DoubleComputepay () {System. out. println ("Inside Employee Computepay"); return 0.0; }    Public voidMailCheck () {System. out. println ("Mailing a check to"+ This. Name+" "+ This. Address); }    PublicString toString () {returnName +" "+ Address +" "+Number ; }    PublicString GetName () {returnname; }    PublicString getaddress () {returnaddress; }    Public voidsetaddress (String newaddress) {address=newaddress; }    Public intGetNumber () {returnNumber ; }}

Notice that the employee class is not different, although the class is abstract, but it still has 3 member variables, 7 member methods, and a constructor method. Now if you try the following example:

 Public classabstractdemo{ Public Static voidmain (String [] args) {/*The following are not allowed and will throw an error, the compilation does not pass*/Employee e=NewEmployee ("George W.","Houston, TX", +); System. out. println ("\ n Call mailcheck using Employee reference--");    E.mailcheck (); }}

When you try to compile the Abstractdemo class, the following error occurs:Employee is abstract; cannot be instantiated

Second, inherit abstract class:

We can inherit the employee class in a general way:

 Public classSalary extends employee{Private DoubleSalary//Annual Salary    PublicSalary (string name, string address,intNumberDoublesalary)       {Super (name, address, number);   Setsalary (Salary); }    Public voidMailCheck () {System. out. println ("within MailCheck of Salary class"); System. out. println ("Mailing Check to"+GetName ()+"With salary"+salary); }    Public Doublegetsalary () {returnsalary; }    Public voidSetsalary (Doublenewsalary) {       if(Newsalary >=0.0) {Salary=newsalary; }   }    Public DoubleComputepay () {System. out. println ("Computing salary pay for"+getName ()); returnsalary/ the; }}

Although we cannot instantiate an object of an employee class, if we instantiate a salary class object, the object inherits 7 member methods from the employee class, and the method allows you to set or get three member variables.

 Public classabstractdemo{ Public Static voidmain (String [] args) {Salary s=NewSalary ("Mohd Mohtashim","Ambehta, up",3,3600.00); Employee e=NewSalary ("John Adams","Boston, MA",2,2400.00); System. out. println ("Call MailCheck using Salary reference--");      S.mailcheck (); System. out. println ("\ n Call mailcheck using Employee reference--");    E.mailcheck (); }}

Third, abstract methods:

  If you want to design a class that contains a special member method whose implementation is determined by its subclasses, you can declare the method as an abstract method in the parent class.

The abstract keyword can also be used to declare an abstraction method, which contains only one method name and no method body.

Abstract methods are not defined, followed by a semicolon, not a curly brace, directly following the method name.

 Public Abstract class employee{   private  String name;    Private String address;    Private int Number ;     Public Abstract double Computepay (); // abstract Methods    // remaining code }

Declaring an abstract method can result in the following two results:

(1) If a class contains an abstract method, the class must be an abstract class.

(2) Any subclass must override the abstract method of the parent class, or declare itself an abstract class.

Subclasses of inherited abstract methods must override this method. Otherwise, the subclass must also be declared as an abstract class. Eventually, a subclass must implement the abstract method, otherwise, from the original parent class to the final subclass, it cannot be used to instantiate the object.

If the salary class inherits the employee class, it must implement the Computepay () method:

 Public classSalary extends employee{Private DoubleSalary//Annual Salary    Public DoubleComputepay () {//the salary class inherits the employee class, and it must implement the Computepay () methodSystem. out. println ("Computing salary pay for"+getName ()); returnsalary/ the; }   //The rest of the code}

Iv. Summary of abstract class provisions:

1. Abstract classes can not be instantiated (beginners are prone to make mistakes), if instantiated, will error, compile cannot pass. Only non-abstract subclasses of abstract classes can create objects.

2. Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.

3. Abstract methods in abstract classes are simply declarations that do not contain method bodies, but do not give concrete implementations of the methods (that is, the specific functions of the method).

4. A constructor method, a class method (a static decorated method) cannot be declared as an abstract method.

5. Subclasses of an abstract class must give a concrete implementation of an abstract method in an abstract class, unless the subclass is also an abstract class.

6, the child abstract class inherits the parent abstract class, must explicitly call the parent abstract class's dominant constructor.

Abstract classanimal{Private intAge ;  PublicAnimal (intAge ) {         This. Age =Age ; System. out. println ("Initialize Animal"); }     Public voidMove () {System. out. println ("number of runs:"+ This. Age); }}Abstract classDog extends animal{//Child abstract class inherits parent abstract class     PublicDog (intAge ) {super (age);//Remove the report exception: explicit constructors that must explicitly call the parent abstract classSystem. out. println ("Initialize Dog"); }} Public classBigDog extends dog{ PublicBigDog () {Super (Ten);//calledSystem. out. println ("Initialize BigDog"); }     Public Static voidMain (string[] args) {BigDog a=NewBigDog ();    A.move (); }}

Java Basics (ix): abstract classes

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.