Java Abstract class

Source: Internet
Author: User

Java Abstract class

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.

Abstract class

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

Employee.java File Code:
/*file name: Employee.java*/ 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"); return0.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:

Abstractdemo.java File Code:
/**/Publicclass  abstractdemo{   publicstatic  void  main (String [] args)   {      /** *        New Employee ("George W.", "Houston, TX", "Max");       System.out.println ("\ n call MailCheck using Employee reference--");      E.mailcheck ();    }}

When you try to compile the Abstractdemo class, the following error is generated:

Abstract ; cannot be instantiated       New Employee ("George W.", "Houston, TX");                    ^1 Error

Inheriting abstract classes

We can inherit the employee class in a general way:

Salary.java File Code:
/*file name: Salary.java*/ Public classSalaryextendsemployee{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/52; }}

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.

Abstractdemo.java File Code:
/*file name: Abstractdemo.java*/ 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 (); }}

The results of the above program compilation Run as follows:

constructing an employeeconstructing an employeecall mailcheck using   --Class 3600.0 callMailCheck using Employee reference-class  2400.

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 ();       // remaining code }

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

    • If a class contains an abstract method, the class must be an abstract class.
    • 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:

Salary.java File Code:/
/**/Publicclassextends    employee{Private  Double//  Annual salarypublic     double  Computepay ()   {      System.out.println("Computing salary pay for" + GetName ());       return salary/52;   }     // remaining code }

Abstract class Summary 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 only declarations, do not contain method bodies, that is, the concrete implementation of the method is the specific function 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.

List of Notes
  1. Abstract classes in Java cannot be instantiated

    code example:
    class Abstract A {}

    Drive function:

     Public Static void   Main (string[] args) {   // The following line causes the compilation not to pass    a a=new  A ();}

    Reference address

  2. The child abstract class inherits the parent abstract class and must explicitly call the dominant constructor of the parent abstract class

    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 classDogextendsanimal{ PublicDog (intAge ) {    Super(age);//get rid of the report exceptionSYSTEM.OUT.PRINTLN ("Initialize Dog"); }} Public classBigDogextendsdog{ PublicBigDog () {Super(10); System.out.println ("Initialize BigDog"); }   Public Static voidMain (string[] args) {BigDog a=NewBigDog ();  A.move (); }}

Java Abstract class

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.