"Getting Started with Java" Day3 abstract class and interface comparison

Source: Internet
Author: User
Tags modifiers

Abstract class and interface are finished, now to do a comparison.

In fact, to be honest, there is not much comparability, they are completely different two things, their abstraction is not at the same level. But in order to let everyone better understand, or make a comparison, after all, they are very abstract (233).

  The first is the grammatical level of contrast.

1) abstract classes and interfaces cannot be instantiated , because they are very virtual. However, there are some differences in access rights.

An abstract method in an abstract class (which has an abstract decoration before it) cannot be decorated with private, static, synchronized, native access modifiers. The reason is very simple, allow me to slowly.

Abstract method is not a method body, its purpose is to inherit, so if the use of private decoration, can not be inherited it? This violates its design intent, so it is not possible to use private to modify the abstract method. As for static, the method used to modify it can be called directly without instantiation, but there is no method body for the abstract method, and there is no point in using static modification. Synchronized is used to lock, if the method in the decorated class, it is equivalent to use this variable lock, but the abstract class can not be instantiated, the abstract method is not implemented in this class but in the subclass, so the lock should be a subclass belongs to, Therefore, abstract methods can not be modified with the Synchronized keyword, as for native, this is a conflict with the abstract keyword itself, the abstract declaration method is given to the subclass implementation, and native is given to the local operating system implementation, if it appears at the same time, That is equivalent to the implementation of the sub-class, and to the local operating system, then who will finally be implemented?

In summary, abstract methods in abstract classes can only be modified with public and protected.

B. The methods in the interface are all public abstract decorated, cannot use other modifiers, and the default (without any modifiers), is also public abstract, because the interface can only be implemented by the class, cannot be inherited by the class, so you cannot use the protected adornment, However, an interface can inherit an interface.

2) The only difference between abstract classes and ordinary classes is that they cannot be instantiated and can have abstract methods, so it can have constructors, static methods, static blocks of code, and can have common member variables and methods. But the interface is different, and the interface can only declare public abstract methods and public static final member variables.

3) Abstract class is essentially a class, can only be inherited, a class can inherit only one abstract class, but can implement multiple interfaces.

  The second is the conceptual comparison

1) Abstract class is not the same as the abstract angle of the interface , abstract class is generally for some similar properties and methods of the abstract class, abstract a unified parent class. The interface is more of an abstraction of a particular set of behaviors, and the focus is on behavior, and there may not be much association between classes with these behaviors.

For example, the plane can heaven, the bird can heaven, if you are strong, you should also be able to Heaven (escape), but obviously the relationship between the two is not very small, if you just want to plug them into a common parent, it seems unreasonable, it looks like this:

  

 Public Abstract class Flyer {    publicabstractvoid  fly ();}

Then define two classes to inherit from it:

 Public class extends Flyer {    @Override    publicvoid  Fly () {        System.out.println ("airplane is flying. " );    }}
 Public class extends Flyer {    @Override    publicvoid  Fly () {        System.out.println ( "Bird is flying." );    }}

OK, now write a test class:

 Public class Test {    publicstaticvoid  main (string[] args) {        new Flyer[2];        flyer[New  airplane ();        flyer[New  Bird ();          for (Flyer f:flyer) {            f.fly ();     }}}

The results of the operation are as follows:

Airplane is flying. Bird is flying.

At first glance, it seems to run well, but think about it, the two low-correlation classes forcibly inserted into a parent class, it seems to be a bit inappropriate, after all, aircraft and birds in addition to fly, basically there is no similar place, and the two flight methods, flight speed and height are far from, that is, in addition to this fly method, Other methods are implemented in their subclasses, and a class can inherit only one abstract class, so the bird class and the airplane class cannot inherit other classes, which in turn limits the flexibility of the program. So, at this time, it is still more appropriate to use the interface:

 Public Interface iflyable {    // declaration Fly method    void  fly ();}

At this point, you only need to change the airplane class and bird class extends flyer to implement Flyable.

 public  class  airplane implements   iflyable { //
     Implement the Fly method   @Override  public  void   Fly () {SYSTEM.OUT.P Rintln ( "Airplane is flying.")    
 Public class Implements iflyable {    // Implement Fly method     @Override    publicvoid Fly () {        System.out.println ("Bird is flying.") );    }}

Modify the test class again:

 Public class Test {    publicstaticvoid  main (string[] args) {        new Iflyable[2];        flyer[New  airplane ();        flyer[New  Bird ();          for (iflyable f:flyer) {            f.fly ();     }}}

The output is as follows:

Airplane is flying. Bird is flying.

Perhaps from this chestnut can not clearly see the difference between the two, then we change a chestnut, people can fly, can take the train, but also can ride a car, as long as they have a manned function, the interface is implemented as follows:

 Public Interface Icarrypassenger {    // declaration passenger method    void  carry (passenger passenger);}

Define a passenger class that distinguishes each passenger by its name.

 Public classPassenger {PrivateString name;//Passenger Name     Publicpassenger (String name) { This. Name =name; }     PublicString GetName () {returnname; }    //How to travel     Public voidTravelby (Icarrypassenger ic) {Ic.carry ( This); }}

Respectively define the car class, train class, aircraft class, they all implement Icarrypassenger interface, aircraft can also implement Iflyable interface (although not used). ):

 public  class  Car implements   Icarrypassenger { int<    /span> Passengernum;      //  implement carry method   @Override  public  void   carry (passenger passenger) {SYSTEM.OUT.PRINTLN (" Passenger: "+passenger.getname () +" Travel b Y Car. "         ++; SYSTEM.OUT.PRINTLN ( Car carries: "+passengernum+" passenger. ")    
 Public class Implements Icarrypassenger {    int  passengernum;    @Override    publicvoid  carry (passenger passenger) {        System.out.println ( "Passenger:" +passenger.getname () + "travel by Train." );        Passengernum+ +;        System.out.println ("Train carries:" +passengernum+ "passenger." );    }}
 Public classAirplaneImplementsiflyable,icarrypassenger{Private intPassengernum;//number of passengers//implementing the Fly method@Override Public voidFly () {System.out.println ("Airplane is flying."); }    //implementing the Carry Method@Override Public voidcarry (passenger passenger) {SYSTEM.OUT.PRINTLN ("Passenger:" +passenger.getname () + "travel by airplane."); Passengernum++; System.out.println ("Airplane carries:" +passengernum+ "passengers."); }}

OK, now let's write a test class to test:

 Public classTest { Public Static voidMain (string[] args) {//There are 6 passengers who want to travel, no emphasis on the way of travel, random distribution of vehiclesRandom random =NewRandom (); Passenger[] Passengers=NewPASSENGER[6];//Declaration of 6 passengers         for(inti=0;i<6;i++) {Passengers[i]=NewPassenger ("passenger[" +i+ "]"); } icarrypassenger[] ICP=NewICARRYPASSENGER[3];//declare 3 modes of transportationIcp[0] =Newairplane (); icp[1] =NewCar (); icp[2] =NewTrain ();  for(inti=0;i<6;i++) {Passengers[i].travelby (Icp[random.nextint (3)]); }    }}

The output is as follows:

Passenger:passenger[01 passengers. passenger:passenger[11 passenger. passenger:passenger[22 passengers. passenger:passenger[31 passenger. passenger:passenger[42 passenger. passenger:passenger[53 passengers.

Because there is not much connection between the plane and the train, the car, obviously cannot abstract the parent directly, they only have the same behavior, that is the passenger, so the use of the interface is the most appropriate.

So far, this article explained, presumably through this explanation, for the abstract class and interface differences should have a better understanding of it, if there is a better chestnut, welcome message exchange, also welcome everyone to continue to pay attention to.

"Getting Started with Java" Day3 abstract class and interface comparison

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.