Java Basic Series Preliminary finishing

Source: Internet
Author: User
Tags modifier

"Java Basic Series" preliminary finishing about 12 articles, the main content is. :

Abstract classes and Interfaces
Inner class
Modifier
Packing Box Unpacking
Annotations
Reflection
Generic type
Abnormal
Collection
Io
String
Other
First, let's talk about abstract classes and interfaces.

"Abstract classes and Interfaces" sounds a very common thing, some friends will think: This is too basic, there is nothing to say, you again to deceive me.

Write a picture description here

In fact, I was asked in the interview not only once about the relevant questions:

What is the difference between an abstract class and an interface?
When do I create an abstract class? When do I create an interface?
How do I choose when designing a framework?
I prefer this question, the answer can be deep and shallow, reflects our thinking about the daily work.

When will we create an abstract class? When will an interface be created? How do you choose to change your mind, not just to complete the function, but to ensure a stable and flexible scalability of the entire project architecture?

We try to answer these questions in this article and hope you can say your answer.

What are abstract classes and interfaces

Abstract methods are decorated with the abstract keyword, and only methods that declare no method body are available.

public abstract void f (); No content
1
An abstract class is a class that contains an abstract method.

If a class contains one or more abstract methods, the class must be qualified as abstract. Abstract classes can contain no abstract methods.

Public abstract class Baseactivity {
Private final String TAG = This.getclass (). Getsimplename (); Abstract classes can have members

void log (String msg) {//abstract class can have specific methods
SYSTEM.OUT.PRINTLN (msg);
} is a special form of an abstract class that is decorated with interface.

Public interface Onclicklistener {
void OnClick (View v);
}
1
2
3
Features and differences

Characteristics of abstract Classes

Abstract class is originally intended to be "abstract", that is, the definition of the class "What", the specific implementation of the temporary uncertainty, is incomplete, and therefore does not allow the creation of an instance directly.

An abstract class is an abstraction of the same class of features as a subclass or a base class or a parent class.
The abstract method must be public or protected (because if you are private, you cannot inherit from the quilt class, the subclass cannot implement the method), and by default it is public
Abstract classes cannot be used to create objects
Abstract methods must be implemented by subclasses
If a class inherits from an abstract class, the child class must implement the abstract method of the parent class, and if the subclass does not implement an abstract method of the parent class, the subclass must also be defined as an abstract class
Abstract classes are also useful refactoring tools because they make it easy to move public methods up the inheritance hierarchy
Features of the interface

Java in order to ensure that data security is not much inheritance, that is, a class has only one parent class.

However, the interface is different, a class can implement multiple interfaces at the same time, regardless of the relationship between these interfaces, so the interface to compensate for the abstract class can not inherit more defects.

An interface is an extension of an abstract class that defines a method that does not have a method body and requires the implementation to implement it.

All method access rights for an interface are automatically declared as public
The "member variable" can be defined in an interface and automatically becomes a static constant of the public static final decoration
Direct access via class naming: Www.yibaoyule1.com implementclass.name
Creating a constant class using an interface is not recommended
The non-abstract class that implements the interface must implement all the methods in the interface, and the abstract class can not implement all
Interfaces cannot create objects, but can declare an interface variable for easy invocation
Fully decoupled, you can write code that is more reusable
Chestnuts

The front says too much, we directly on the code.

Let's say we start a new project and we need to write a lot of activity that will have some common properties and methods, so we'll create a base class that puts these common methods in:

public class Baseactivity extends Activity {
Private final String TAG = This.getclass (). Getsimplename ();

void Toast (String msg) {
Toast.maketext (This, MSG, Toast.length_short). Show ();
}
Other repetitive work, such as setting the title bar, immersive status bar, detecting network status, etc.
At this point, Baseactivity is a base class whose role is to encapsulate duplicate content.

Writing, we found that some colleagues code is too bad, a method of hundreds of lines of code, watching too painful. Therefore, in the spirit of "separation of duties" principle, we created some abstract methods in baseactivity, requiring subclasses to implement:

Public abstract class Baseactivity extends Activity {
Private final String TAG = This.getclass (). Getsimplename ();

@Override
protected void OnCreate (final Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (www.qinlinyu.cn Getcontentviewlayoutid ());

Initview (); Here to initialize the layout
LoadData (); Load the data here
}

/**
* methods that require subclasses to implement
* @return
*/
protected abstract int Getcontentviewlayoutid ();
protected abstract void Initview ();
protected abstract void LoadData ();

void Toast (String msg) {
Toast.maketext (This, MSG, Toast.length_short). Show ();
The defined abstract method access modifier can be public protected and default, but cannot be private because such subclasses cannot be implemented.
At this time baseactivity because of the abstract method, became an abstract class. It does this by defining the specification, forcing the subclass to conform to the standard, and, if you call an abstract method, a rule that executes the order.

Classes that inherit baseactivity can guarantee the cleanliness of the code as much as the parent class, as long as the methods are implemented and the parent class is provided with the required content.

public class Mainactivity extends baseactivity{

Private TextView Mtitletv;

@Override
protected int Getcontentviewlayoutid () {
return r.layout.activity_main;
}

@Override
void Initview () {
Mtitletv = (TextView) Findviewbyid (R.ID.MAIN_TITLE_TV);
Mtitletv.setonclicklistener (this);
}

@Override
protected void LoadData () {
Load the data here
Later, if you find that there are some functions in different Activity repeated more times, you can refer to the implementation of this feature in Baseactivity. But be careful not to add abstract methods easily, as this will affect the previous subclass.

The project writes that it is found that many pages have been re-requested according to the location information change, in order to facilitate management, and then put such code into baseactivity? Yes, but that's not how the code that doesn't need to be located is "contaminated", and too much redundant logic baseactivity not become a hodgepodge.

We want to put the location-related to another class, but Java has only one inheritance, then we can use the interface.

We create an interface that represents the monitoring of a geographic location:

Interface Onlocationchangelistener {
void Onlocationupdate (String locationinfo);
}
1
2
3
The interface is public by default and cannot be used with other modifiers.
The reference to this interface is then held in a position observer:

public class Locationobserver {

List<onlocationchangelistener> mlisteners;

Public Locationobserver setlisteners (final list<onlocationchangelistener> listeners) {
Mlisteners = listeners;
return this;
}

Public list<onlocationchangelistener> getlisteners () {
return mlisteners;
}

public void Notify (String locationinfo) {
if (mlisteners! = null) caihonyule.com/{
for (Onlocationchangelistener listener:mlisteners) {
Listener.onlocationupdate (Locationinfo);
}
}
}

Interface Onlocationchangelistener {
void Onlocationupdate (String locationinfo);
This allows us to implement this interface in a page that needs to be located:

public class Mainactivity extends baseactivity implements View.onclicklistener,
Locationobserver.onlocationchangelistener {

Private TextView Mtitletv;

@Override
protected int Getcontentviewlayoutid () {
return r.layout.activity_main;
}

@Override
public void OnClick (final View v) {
int id = V.getid ();
if (id = = R.ID.MAIN_TITLE_TV) {
Toast ("You clicked the title");
}
}

@Override
void Initview () {
Mtitletv = (TextView) Findviewbyid (R.ID.MAIN_TITLE_TV);
Mtitletv.setonclicklistener (this);
}

@Override
protected void LoadData () {
Load the data here
}

@Override
public void Onlocationupdate (final String locationinfo) {
Mtitletv.settext ("Present position is:" + locationinfo);
This mainactivity has the ability to monitor position changes.

If you need to add additional functionality in Mainactivity, you can create the corresponding interface and then implement it.

Summary

With the code example above, we can clearly understand what is summarized in the following diagram.

Write a picture description here

Photo from: http://www.jianshu.com/www.huachengjpt.com p/8f0a7e22bb8c
We can see these differences in abstract classes and interfaces:

Different levels of abstraction
Abstract classes are abstractions of classes, and interfaces are abstractions of behavior
Abstract classes are abstractions of the whole class as a whole, including properties, behaviors, but interfaces that abstract the local behavior of a class
Different across domains
An abstract class spans a class with similar characteristics, whereas an interface can span different classes of domains
Abstract class embodies a kind of inheritance relationship, considering the relationship between the subclass and the nature of the parent class is not the same class
And the interface does not require the implementation of the class and interface is the same essence, there is only "have this ability" relationship between them
Different design levels
Abstract classes are bottom-up design, repetitive work in subclasses, abstracted into abstract classes
Interfaces are top-down, defining behaviors and specifications
How to choose

Now we know that abstract classes define "what", can have non-abstract properties and methods, interfaces are more pure abstract classes, in Java can implement multiple interfaces, so the interface represents "what is the ability."

When making a selection, you can refer to the following points:

If we use interfaces, we can get the benefits of both abstract classes and interfaces.
So if you want to create a base class that doesn't have any method definitions or member variables, you're willing to use the interface anyway instead of the abstract class.
If you know beforehand that something is going to be a base class, then the first option is to turn it into an interface.
You should consider using abstract classes only when you must use a method definition or member variable
In addition, one of the most important reasons to use an interface is to implement an interface that transforms a class up to multiple base classes.

For example, the common interface such as Serializable and cloneable, a class implementation will represent these capabilities, it can be treated as Serializable and cloneable.

The recommended interface is used in conjunction with the abstract class, which ensures the security of the data and enables multiple inheritance.
Abstraction and polymorphism

As the saying goes: "Work to stay on the line, future good meet."

Program development is also the same, it is a continuous increase or accumulation of the process, it is impossible to perfect at once, so we have to give as far as possible to modify the room, and this requires us to use the legendary "object-oriented three characteristics"-inheritance, encapsulation, polymorphism.

Whether using an abstract class or an interface, the final grounding or the separation of duties as far as possible, the business abstraction, that is, "interface-oriented programming."

Interface-Oriented Programming

When you make an appointment with someone in your daily life, don't be too specific about it. Like when people ask us when we are free, back to a "about in the winter" must be more flexible than "This Saturday noon", who knows this Saturday will suddenly have any changes.

When we write code, we pursue "status quo", which can be implemented with as few modifications as possible when requirements change.

In this case, it is best to rely on the abstract interface given by each other, rather than the specific implementation, when dependencies between modules are needed.

This is the "dependency inversion principle" in design mode, which is implemented in three ways:

Passing a dependent object through a constructor function
For example, in a constructor, a parameter that needs to be passed is an abstract class or interface implementation
Passing dependent objects through setter methods
That is, the arguments in the Setxxx method we set are abstract classes or interfaces to implement transitive dependent objects
Interface declarations implement dependent objects, also called interface injection
That is, in the function declaration, the argument is an abstract class or interface, which implements the transitive dependent object, thus achieving the purpose of directly using the dependent object.
As you can see, "interface-oriented programming" also includes abstract classes, in fact, the base class, the easier the better.
Polymorphic

Polymorphism refers to the compilation period is only known to the individual, specifically what kind of people need to be able to determine at run time, the same parameters may have different implementations.

Through the abstract establishment of norms, at run time to replace the specific objects, to ensure the scalability of the system, flexibility.
There are three main ways to achieve polymorphism:

Interface implementation

Inheriting the parent class override method

Method overloading in the same class

Either way, the caller holds the base class, and the different implementations seem to him to be base classes, which are used as base classes.

This is an "upward transformation", in which the subclass is transformed from below the inheritance relationship to the above role in the called process.

The upward transformation is the process of reducing capacity, and the compiler can help us, but "downward transformation" is the process of strong power, which requires a strong turn.
Take the code above as an example:

public class Locationobserver {

List<onlocationchangelistener> mlisteners;

Public Locationobserver setlisteners (final list<onlocationchangelistener> listeners) {
Mlisteners = listeners;
return this;
}

Public list<onlocationchangelistener> getlisteners () {
return mlisteners;
}

public void Notify (String locationinfo) {
if (mlisteners! = null) www.xyseo.net/{
for (Onlocationchangelistener listener:mlisteners) {
Locationobserver holds a reference to Onlocationchangelistener, regardless of whether the runtime is mainactivity or other Activity, as long as the interface is implemented, the implementation method can be called.

At compile time, you know which method to invoke, called "early binding" (also known as "static Binding"), which is implemented by the compiler and the linker.

Invoking the correct method at run time, this process is called "dynamic binding", in order to implement dynamic binding, there is a mechanism to invoke the appropriate method at run time depending on the type of object. This mechanism is implemented by the virtual machine, the invokevirtual instruction will parse the constant pool class method symbol reference to different references, this process is called "Dynamic dispatch", the specific implementation process we do not discuss.

Inheritance and composition

Although inheritance has been heavily emphasized in learning OOP, it does not mean that it should be used everywhere as much as possible.

On the contrary, use it with caution, because inheriting a class means you need to accept everything, whether you have to accept him or not, and you can do it.

The average person is unable to grow old, so you can only consider it if you know exactly what you need to inherit all the methods.

One way to replace inheritance is to "combine".

A combination is to have everything by holding a reference to a class, rather than inheriting, passing in a reference when the method needs to be called, and then invoking it, or clearing the reference.

The combination is more flexible than inheritance, and the inheritance represents the "is-a" relationship, but the combination is the "has-a" relationship.

One of the simplest ways to determine if you should choose to synthesize or inherit is to consider whether you need to change from a new class up to the base class.

If you do need to turn upwards, use inheritance, but if you don't need to go back to styling, you should remind yourself to prevent abuse of inheritance.

Summarize

The purpose of this article is to help readers understand and grasp the characteristics of abstract classes and interfaces and different usage scenarios, which are written with a few more nagging words and hope to help you.

The purpose of this series is to help you systematically, complete the foundation, and gradually deep learning, if you are already very familiar with these, please do not skimp on your evaluation, more points out the problem, we do Better Together!

Java Basic Series Preliminary finishing

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.