The three features of object-oriented in Java and UML

Source: Internet
Author: User
Tags access properties lenovo

Object-oriented, no matter what programming language, there are three features: encapsulation, inheritance, polymorphism.

First, the package:

For example, such as computer, computer is a class, outside some USB sockets, you know, the printer can be printed on the plug, the audio plug can be put music, but you do not know how the internal computer is implemented, you just know that this interface does have these features, you can use, so, for ordinary users, They don't know the computer, they can use it, they don't destroy things inside the computer. And developers are reserved for these interfaces, to protect the computer will not be broken by unprofessional people.

Encapsulation is to do this thing, class is a black box, reserved several interfaces for others to use, how to achieve the use of the people do not need to know.

For example, there is a computer class, properties: Brand, model two, so that the outside can access the two properties through the interface, but not directly to the property access. The code is as follows:

/*** @author leigao* @data 2016.11.19*/class computer{//to privatize two properties, which is not accessible outside. The private string Brand;private string type;//implements the interface of two properties, that is, using a method as an interface, as follows: Public String Getbrand () {return brand;} public void Setbrand (String brand) {This.brand=brand;} Public String GetType () {return type;} public void SetType (String type) {This.type=type;}} Specify the program entry: class Computermain{public static void Main (string[] args) {Computer computer = new computer ();//The following two statements will error:// Computer.brand= "Lenovo";//computer.type= "ThinkPad"//Set properties and Access properties by interface//Set properties Computer.setbrand ("Lenovo"); Computer.settype ("ThinkPad");//access property String brand = Computer.getbrand (); String type = Computer.gettype (); System.out.println ("Brand:" +brand+ "\ n type:" +type);}}

Note: The Java permission modifier is before the member variable and the member method, that is, the properties and functions of the class. It mainly restricts the access of foreign personnel to ensure its safety. Specific permissions, such as:

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M00/8A/6D/wKioL1gv40WC8J5tAAGlFD6nKXk142.png-wh_500x0-wm_3 -wmp_4-s_729210612.png "title=" Quanxian.png "alt=" Wkiol1gv40wc8j5taaglfd6nkxk142.png-wh_50 "/>

As can be seen, as a member of the interface or function method, is intended to let other modules or other people to use, so in addition to special circumstances, the basic is modified with public, as the class of the attributes of the member variables, in order to protect, the basic use of private decoration, the other keywords are seldom used.


Second, inheritance:

The so-called inheritance, is the son of the father, since the inheritance of fathers, then the father will, the children will, the father will not, the children can also, or how to make progress? Of course the private decorated child does not, but the public is modified to have, therefore, the properties of the private modified interface, setter and getter method, still useful.

The UML class diagram is as follows:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M01/8A/6D/wKioL1gv5ivTSXxKAAAp8K8XOLo275.png-wh_500x0-wm_3 -wmp_4-s_3360531758.png "title=" Class3.png "alt=" Wkiol1gv5ivtsxxkaaap8k8xolo275.png-wh_50 "/>

According to the implementation of the code is as follows:

/** *  @author  LeiGao24 *  @data  2016.11.19 */  class person{  private String name; private String sex; private Integer age;   public void sleep () { system.out.println ("person sleep  ..."); }   public void eat () { system.out.println ("person eat  ...");  }  // Interface for member variables//name interface  public void setname (string name) { this.name=name; } public  string getname () { return name; }//sex interface  public void setsex (String  sex) { this.sex=sex; } public string getsex () { return sex; }// Age Interface  public void setage (integer age) { this.age=age; } public integer  getage () { return age; } }  class teacher extends person{  //teacher School PRIVATE&NBsp string school; //member Method  public void teach () { system.out.println ("teacher   teach  method ... ");  }  //school interface  public void setschool (string school { this.school=school; } public string getschool () { return school; }  }  class student extends person{ //students belong to class, because class is the keyword, so write as clsprivate  string cls; //member Method  public void study () { system.out.println ("student    study  method ... ");  }  //school interface  public void setcls (STRING CLS) {  This.cls=cls; } public string getcls () { return cls; } }  // Program Entry  class personmain{ public static void main (String[] args) { //created:// Person: Zhang San, male, 21 years old//teacher: John Doe, male, 30 years old, Tsinghua High School//students: Wang, female, 18, 32 class System.out.println ("****** people **********"); person person = new Person ();p erson.setname ("Zhang San");p erson.setsex ("male");p Erson.setage (21); System.out.println ("Name:" +person.getname () + "\ n Sex:" +person.getsex () + "\ n Age:" +person.getage ()); System.out.println ("******* teacher *******"); Teacher teacher = new teacher (); Teacher.setname ("John Doe"); Teacher.setsex ("male"); Teacher.setAge ( Teacher.setschool ("Tsinghua University"); System.out.println ("Name:" +teacher.getname () + "\ n Sex:" +teacher.getsex () + "\ n Age:" +teacher.getage () + "\ n School:" + Teacher.getschool ()); System.out.println ("******* student ********"); Student student= new student (); Student.setname ("Wang"); Student.setsex ("female"); Student.setAge (18); Student.setcls ("High 32 classes"); System.out.println ("Name:" +student.getname () + "\ n Sex:" +student.getsex () + "\ n Age:" +student.getage () + "\ n class:" + Student.getcls ());  } }

Operation Result:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M01/8A/6D/wKioL1gv7Xfil6dmAAAS9T0YHX8983.png-wh_500x0-wm_3 -wmp_4-s_2575578691.png "title=" Resultresulr.png "alt=" Wkiol1gv7xfil6dmaaas9t0yhx8983.png-wh_50 "/>


Finally, polymorphism:

Polymorphism is the same thing but there are many forms, or the type is more, but essentially a thing, such as refrigerators, this is a thing, but also a lot of classes, such as Haier, the United States, and many other brands. is essentially a thing, and that is polymorphism.

There are two kinds of polymorphism: one is run-time polymorphic, and the other is compile-time polymorphism.

run-time polymorphic, is the example above the refrigerator, the refrigerator is a class, Haier is a class, there are refrigeration methods, but Haier refrigerator will be rewriting the method of refrigeration. This multiple class, the way between classes overrides, is run-time polymorphism .

compile-time polymorphism, for example, when eating hot pot, put in vegetables, cooked is a dish, put in meat cooked is meat, and no meat a pot, vegetable a pot, but in a pot, you put in what, he is according to you put things to deal with, this in a class inside, There are multiple methods of the same name, but the method is not the same as the parameter implementation, called overloading , that is, compile-time polymorphism.


There are three ways to implement polymorphism:

The first, the implementation of the interface

The second type, inheritance

Third, the realization of abstract class

The so-called interface, is a way to extend the class, similar to the USB interface on the computer. For example, the mobile phone class inheritance relationship. Such as:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M02/8A/6E/wKioL1gv9cKAI8qOAAAZI6hkCT8925.png-wh_500x0-wm_3 -wmp_4-s_2427723300.png "title=" Jiekou.png "alt=" Wkiol1gv9ckai8qoaaazi6hkct8925.png-wh_50 "/>

From what we see, Samsung, Apple, Nokia are mobile phones, so is the inheritance relationship (with "is-a" to express the relationship), but we will find Samsung and Apple phones and play games and movies, since all have, in order to reduce the amount of code, we can pull them out, But after extracting it can not redefine a class, because playing games and watching movies only two methods, there is nothing like this, "Note: Do not extract out on a class, it must be the real class, real can be categorized in reality, not to inherit and write class", since can not set up a class, And playing games and watching movies These two features are actually the expansion of Samsung and Apple class of smartphones, so we can directly extract to write an interface. The UML diagram is as follows:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M02/8A/72/wKiom1gv97uSF_YwAAAay1Fsu28461.png-wh_500x0-wm_3 -wmp_4-s_1611595583.png "title=" Inteface.png "alt=" Wkiom1gv97usf_ywaaaay1fsu28461.png-wh_50 "/>


The second way, inheritance, we have been approached several times.

The third way, the implementation of abstract classes, both inherited and interface features

     For example, the following code is an abstract class, abstract decoration, as long as there is an abstract method, this class is an abstract class, using the Inheritance keyword extends, once the interface implementation must implement all the methods in the interface, Abstract classes are not required. The following code shows:

/*** @author  leigao24* @data  2016.11.19*///define a phone class class phone{private string brand; private string size;//property Setter and Getter Method Public void setbrand (String brand) {This.brand  = brand;} Public string getbrand () {Return brand;} Public void setsize (string size) {this.size=size;} Public string getsize () {return size;}} Define an interface//interface only defines the extension function, which is the method, and the method//no method body, that is, no curly braces that part interface func{public void playgame ();p ublic  void movies ();} Define an abstract class://abstract class and ordinary class, the inside can have properties and methods,//method can have method body, also can not, and interface must//no method body abstract class funccls{public  Abstract void playgame ();p ublic void movies () {System.out.println ("Playing games ...");}} Defines a Samsung class, inherits the phone class, implements the interface class sanxing extends phone implements func{//implements all the methods in the interface, If there is a method not implemented,//will be error public void playgame () {System.out.println ("Samsung Play game! ");} Public void movies () {System.out.println ("Samsung Watch movie ... ");}} Define an appleClass, inherited abstract methods, because Java is single-inheritance//So only one class can inherit, but Java is multi-implementation, that is,//interface implementation can be multiple class apple extends funccls{private  string brand;private string size;//implement abstract methods in the abstract class, if you do not implement the//abstract method, then you need to identify the class on the abstract, representing// This class has an abstract method, which is an abstract class. Public void playgame () {System.out.println ("Apple Play Game ...");} Property setter and Getter Method Public void setbrand (String brand) {This.brand = brand;} Public string getbrand () {Return brand;} Public void setsize (string size) {this.size=size;} Public string getsize () {return size;}} Program entry: Class main{public static void main (String[] args) {sanxing sanxing =  new sanxing (); Sanxing.playgame (); sanxing. Movies (); Apple apple = new apple (); Apple.playgame (); Apple. Movies ();}}

Results:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M00/8A/6F/wKioL1gv_q6j_QFfAAAKLp5hMsk407.png-wh_500x0-wm_3 -wmp_4-s_3120284412.png "title=" Sanxing.png "alt=" Wkiol1gv_q6j_qffaaaklp5hmsk407.png-wh_50 "/>


Summary: Abstract classes are common divisor that extract specific classes, and interfaces are meant to "hash" some unrelated classes into a common group. Usually we develop a good habit is a multi-use interface, after all, Java is a single inheritance, only when the implementation of the interface is more implementation.

This article is from the "http://sunshine2624.blog.51cto.com/3959438/1874593" blog, please be sure to keep this source.

The three features of object-oriented in Java and UML

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.