Java Beginner Note No.3 (in update)

Source: Internet
Author: User

2018.7.26

1. Inheritance in Java

In Java, you use extends keywords to describe inheritance relationships.

class Animals {}class Dogs extends Animals {}

2. Characteristics of inheritance

The inherited attributes in Java are basically consistent with C + +:
· Subclasses have properties that are not private in the parent class, methods;
· Subclasses can have their own properties and methods;
· Subclasses can implement the parent class's method (i.e. rewrite) in their own way;
· Inheritance in Java is a single inheritance , but can be multiple inheritance, the single general does not use multiple inheritance, and the use of interfaces to achieve multiple inheritance. This is also different from the inheritance problem in C + +.

3. Inheritance Related keywords

extends
In Java, you use extends keywords to describe single inheritance (a subclass can have only one parent class):

public class Animal {     private String name;       private int id;     public Animal(String myName, String myid) {         //初始化属性值    }     public void eat() {  //吃东西方法的具体实现  }     public void sleep() { //睡觉方法的具体实现  } }  public class Penguin  extends  Animal{ }

Implements
A implements keyword can be used in a disguised manner to make Java have multiple inheritance , using the scope of the class to inherit the interface , you can inherit multiple interfaces (interfaces and interfaces separated by commas):

public interface A {    public void eat();    public void sleep();} public interface B {    public void show();} public class C implements A,B {}

Super and this
superKeyword: used to implement access to a parent class member to refer to the parent class of the current object, which is not allowed in C + +.

thisKeyword: Similar to the this pointer in C + +, except that there is no concept of pointers in Java, this is a reference.

class Animal {    void eat() {        System.out.println("animal:eat");    }}class Dog extends Animal {    void eat() {        System.out.println("dog:eat");    }    void eatTest() {        this.eat();        super.eat();    }}public class testFile {    public static void main(String[] args) {        Animal a = new Animal();        a.eat();                Dog d = new Dog();        d.eatTest();    }}

The methods in the parent class do not have access control permission identifiers, which, by default default , describe the access scope ( default and also the difference from C + +) for each access control identity:

Final

finalThe keyword declaration class can define a class as a class that cannot be inherited , and is also called the final class .

finalKeywords can also be used for individually decorated methods, and the method cannot be overridden by a quilt class:

final class Base {  }  public/private/default/protected final 返回值 method() {  }  

In addition, instance variables can also be defined as final variables that are defined as final not being modified. The method declared as a final class is automatically declared as final , but the instance variable is not final .

4. Constructor function

This is basically the same as the constructors in C + +, where there is a different point:

If the parent class has parameters in its constructor, you must explicitly invoke the constructor of the parent class by keyword in the constructor of the subclass super , with the appropriate argument list.

If the parent class constructor does not have parameters, the constructor for the parent class is not required in the constructor of the subclass super , and the parameterless constructor of the parent class is automatically called:

class SuperClass {    private int n;    SuperClass() {        System.out.println("SuperClass()");    }        SuperClass(int n) {        System.out.println("SuperClass(int n)");        this.n = n;    }}class SubClass extends SuperClass {    private int n;        SubClass() {        super(300);        System.out.println("SubClass()");    }        SubClass(int n) {        System.out.println("SubClass(int n) : " + n);        this.n = n;    }}public class TestSuperSub {    public static void main(String[] args) {        SubClass sc = new SubClass();   //SuperClass(int n), SubClass()        System.out.println();        SubClass sc2 = new SubClass(200);   //SuperClass(), SubClass(int n)    }}

5. Override and Overload

Override-> overrides the,overload-> overload, which is conceptually different from C + +.

Override

When you need to call the overridden method of a parent class in a subclass, you need to use the super keyword:

class Animal{       public void move(){          System.out.println("动物可以移动");       }    }     class Dog extends Animal{   public void move(){      super.move();  //调用Animal的move      System.out.println("狗可以跑和走");   }   public void bark(){      System.out.println("狗可以吠叫");   }}     public class testFile{   public static void main(String args[]){      Animal b = new Dog();      b.move();//执行Dog,但是由于其中调用了super,所以也会输出Animal中的内容   }}

Overload

6. Polymorphism in Java

As with C + +, the existence of polymorphic in Java requires three prerequisites:
· • Inheritance; The parent class reference refers to the child class object.

7. Abstract class
If a class does not contain enough information to depict a specific object, this class is an abstract class that is consistent with the concept of abstract classes in C + + and cannot be used to instantiate objects, primarily for the designation of interfaces.

A pure virtual function is used in C + + to represent an abstract class, and in Java the keyword is used abstract to declare an abstract class:

public abstract class Base {  }

8. Abstract methods
A class contains special member methods that are determined by its subclasses, and can be declared as an abstract method in the parent class:

Abstract methods contain only one method name and no method body.

public abstract class Employee{   private String name;   private String address;   private int number;      public abstract double computePay();      //其余代码}  

Declaring an abstract method can result in two results:
· If a class contains an abstract method, the class must be an abstract class;
· Any subclass must override the abstract method of the parent class, or declare itself an abstract class.

9. Encapsulation in Java
This is no different from the encapsulation in C + +, which is mainly private embodied.

10. Interfaces in Java

The collection of abstract methods in Java is usually interface declared as an interface , which is consistent with the interface in Golang.

[可见度] interface 接口名称 [extends 其他的类名] {        // 声明变量        // 抽象方法}

Interface Usage Examples:

/*AnimalH.java*/package test2;interface AnimalH {    public void eat();    public void travel();}

Class uses implements keywords to implement interfaces.

package test2;public class MammalInt implements AnimalH {    public void eat() {        System.out.println("Mammal eats");    }        public void travel() {        System.out.println("Mammal travels");    }        public int noOfLegs() {        return 0;    }          public static void main(String[] args) {        MammalInt m = new MammalInt();        m.eat();        m.travel();    }}  

11, at the same time, the interface and interface can also be inherited from the relationship, with the extends keyword expression:

// 文件名: Sports.javapublic interface Sports{   public void setHomeTeam(String name);   public void setVisitingTeam(String name);} // 文件名: Football.javapublic interface Football extends Sports{   public void homeTeamScored(int points);   public void visitingTeamScored(int points);   public void endOfQuarter(int quarter);} // 文件名: Hockey.javapublic interface Hockey extends Sports{   public void homeGoalScored();   public void visitingGoalScored();   public void endOfPeriod(int period);   public void overtimePeriod(int ot);}  

12. Multiple Inheritance of interfaces
In Java, multiple inheritance of a class is illegal, but the interface allows multiple inheritance.
In multiple inheritance of interfaces, the Extands keyword only needs to be used once, followed by an inherited interface:

public interface Hockey extends Sports, Event  {}  

A class can implement multiple interfaces, using implements keywords, followed by interfaces implemented:

public class People implements Sports, Event {}  

13. Interfaces without any method are called labeled Interfaces :

Its role is:

13. Packages in Java are concepts that are not in C + +. The existence of a package is to better organize the class, which distinguishes the namespace of the class name.

Import
In order to use a member in a package, you need to explicitly import the package in a Java program and use the import keyword to complete the import of the package.

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.