When does Java use abstract classes and interfaces?

Source: Internet
Author: User

I will summarize the time when abstract classes and interfaces are used.

First, let's look at the following example:

 
Abstract class abstractstudent {abstract void Study (); void sleep () {system. out. println ("Sleep");} void smoke () {system. out. println ("smoke") ;}// all student creation will smoke, isn't it funny? Class student extends actstudent {student demo Stu = new student ();...}

The student's abstract class has three methods: learning, sleeping, and smoking. We know that every student has to study and sleep, but not

Do every student smoke? This is obviously unreasonable. It is hard to say that the method of smoking should be used to create a student object? Just like

When the student comes, he must smoke? Why don't girls leave it alone? Haha! This is obviously ridiculous.

So we made the following adjustments:

Abstract class abstractstudent {abstract void Study (); void sleep () {system. out. println ("Sleep") ;}} interface smoking {void smoke () ;}// common students inherit abstractstudent and have learning and sleeping methods, students who do not smoke class student extends abstractstudent {} // smoke, in addition to inheriting the methods in abstractstudent, smoke class smokestudent extends abstractstudent implements smoking {}

 
 

In this way, the smoking personnel and the non-smoking personnel are separated. Now, do you feel the differences between abstract classes and interfaces?

 

Summary: abstract classes usually include the attributes and Methods common to class-type objects. Therefore, when its subclass inherits from it

Naturally, all its attributes and methods are available. When some methods are unique to a subclass, they should be separated,

Add it as an attachment (implements.

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.