Java (1)-interfaces, inheritance and polymorphism, java (advanced tutorial)

Source: Internet
Author: User

Java (1)-interfaces, inheritance and polymorphism, java (advanced tutorial)

The previous "class and object" was removed from the home page and asked if it was suspected that the Notes could not be posted on the home page. Alas, I felt sorry for myself for a few seconds. It seems that my level is not yet in place, all are written as "Notes. Alas, at present, there are only two or three articles not removed from the home page. Sang Xin, sang Xin, but I can only continue writing this article. I should write the Java part first.

I first wrote this because when I was learning Java a few years ago, I did not find a suitable teaching process for beginners, either not comprehensive, or I was talking about some in-depth Java content, for example, some Java teaching materials and books, many of the basic content mentioned above will be used as an example of future knowledge when listing examples, for example, I once saw a copy (which is not the same here). When I first talked about process control, the example was actually a Java thread example. At that time, it was called a big one, click it and run it to see what you want to express. So I decided to write something about the most basic and core of Java, so that a friend who is interested in Java but is somewhat difficult to learn by himself has a simple learning outline. Of course, another useful part of blog writing is that if Java is not touched for a long time after learning Java, and Java will be used one day in the future, at that time, your own blog is the best review material. For students studying at school, the content of the final exam must be found in my blog post. As for the knowledge points I did not write, it is very difficult to meet them if I do not work in Java. Haha, if you don't believe it, come and look for your final exam. If you don't talk much about it, you just have to complain. Let's take a look at the Java advanced Article below.

 

The first few articles are an introduction to Java. They mainly focus on learning about the Java language. From this article, they are an advanced article on Java, this part of content can help developers develop small applications or small games in Java.

The topic of this article is interface, inheritance and polymorphism. before reading the following content, you must first understand inheritance and polymorphism. The use of the Inheritance Mechanism can reuse some defined classes to reduce repeated code writing. The use of the polymorphism mechanism can dynamically adjust the call of objects to reduce the dependency between objects. With these concepts, let's look at what interfaces are used.

I. Interface

First, we need to know,Java supports only single-inheritance and does not support multi-inheritance.This statement means that a class can only have one parent class, but we often need to use multi-inheritance to solve the problem. Therefore, the Java language provides interfaces to implement multiple inheritance functions of the class.

1. Interface Definition

In Java, interfaces are used to define an interface. The interface definition is similar to the class (class is used for class definition). The following is an example.

Public interface ICalculate {final float PI = 3.1415f; // defines the constant PI, indicating the circumference rate float getArea (float r); // defines the method for calculating the area getArea () float getCircumference (float r); // defines the method for calculating the perimeter getCircumference ()
}

From the code above, we can see that an interface defines an interface named ICalculate (the interface can generally start with an uppercase letter "I"). You can define variables and methods in the interface, however, you must note that none of the methods can be written to the method body, that is, the method name is directly followed by ";", and the implementation of the method is written to the class that implements the interface. Note that all the methods in the interface must be implemented in the class that implements the interface (which can be empty ).

Next, we will demonstrate how to create an interface in Eclipse.

(1) Right-click the package and choose new Interface.

  

(2) Fill in the interface name and confirm

  

(3) write code

  

2. Interface implementation

An interface is defined above, but the implements keyword must be used in the class to implement the interface. Let's look at the example below. The corresponding interface is ICalculate in the above example.

1 public class Calculate implements ICalculate {2 3 @ Override 4 public float getArea (float r) {5 float area = PI * r; // calculate the circular area and assign it to area 6 return area; // return area value 7} 8 9 @ Override10 public float getCircumference (float r) {11 float circumference = 2 * PI * r; // calculate the circumference and assign it to circumference12 return circumference; // return the value of circumference 13} 14 15}

The creation steps in Eclipse are as follows:

(1) enter the class name and click Add to Add an interface.

  

(2) enter the search interface and click OK.

  

(3) After the interface is imported, click "OK". You can see the following interface and enter the corresponding code. (each method in the created interface must be implemented and can be empty, so you cannot delete any method here)

  

A class can implement multiple interfaces, which are separated by commas (,) after implements. If the variable conflict exists, you can use "interface name. Variable" to specify the interface of the variable.

Ii. Inheritance 1. Implementation of Inheritance

In Java, the extends keyword is used to implement inheritance. extends is followed by the parent class name, that is, the class from which it inherits. extends is called a subclass.

The following is a simple example. In biology, a pigeon is a type of bird, so a bird is a parent class and a pigeon is a subclass.

Parent class:

Public class Bird {String color = "gray"; // color String skin = "Feather"; // fur}

Subclass:

public class Pigeon extends Bird {    public static void main(String[] args) {        Pigeon pigeon = new Pigeon();        System.out.println(pigeon.color);    }}
2. Rewrite

Simply put, if the subclass method name and the parent class method name are the same, the subclass method cannot inherit the parent class method. In this case, the method called the subclass method overwrites the method of the parent class. Rewriting is also called overwriting.

For example, this is an animal class that implements a voice method:

public class Animal {  public Animal() {}  public void voice() {        System.out.println("make some voice..");    }}

Create a subclass Dog of the Animal class and rewrite the voice method to generate a Dog name:

public class Dog extends Animal{    public Dog() {}    @Override    public void voice(){        System.out.println("woof...");    }}

Create a sub-class Cat for the Animal class, and rewrite the voice method to send the Cat's name:

public class Cat extends Animal {    public Cat() {}    @Override    public void voice(){        System.out.println("nya...");    }}

In this case, the "make some voise..." is not displayed when you call the methods in dog and cat, but the corresponding dogs and cats.

However, if you create a subclass of the Animal class but do not override the method, output the content of the voice method in the parent class Animal. Create a subclass Fish as follows:

public class Fish extends Animal{    public Fish() {}}

Create a Zoo class to call the above methods for testing:

public class Zoo {    public static void main(String[] args) {        Dog dog = new Dog();        dog.voice();        Cat cat = new Cat();        cat.voice();                Fish fish = new Fish();        fish.voice();    }}

The running result is as follows:

  

From the running results, we can see that because both the Dog class and the Cat class override the voice () method of the parent class, the corresponding method is executed, while the Fish class does not override it, therefore, the method in the parent class is executed.

3. super keyword

Subclass can call the constructor declared by the parent class, but must use the super keyword in the constructor of the Child class; if you want to operate hidden member variables and override member methods in the parent class in the subclass, you can also use the super keyword. These will appear in future projects. Here we will not give an example. If you use the Java compiler, you need to use the super keyword, but the compiler will have an error prompt when it is not used.

Iii. Polymorphism

In Java, method overloading and rewriting are usually used to implement class polymorphism.

As mentioned above, method overloading means that multiple methods with the same name but different parameter numbers or parameter types appear in a class, the following is an example of heavy load.

For example, to calculate the area of a circle and a rectangle, two methods are called getArea (). They have different numbers of parameters, as shown below:

// Calculate the circular area public float getArea (float r) {float area = PI * r; return area;} // calculate the rectangular area public float getArea (float, float B) {// reload the getArea () method float area = a * B; return area ;}

For example, to add a student information, two methods named setStudent () have different parameter types, as shown below:

// Add the student ID public void setStudent (int ID) {this. stu_id = ID;} // Add the Student name public void setStudent (String name) {this. stu_name = name ;}

Note that the type of the return value of a method cannot be used as a flag for distinguishing methods during method overloading.

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.