Day 08Java Basic Learning Notes

Source: Internet
Author: User
Tags instance method

Inheritance extends (also called extension)

When the same properties and behaviors exist in multiple classes, the content is extracted into a single class, so that multiple classes do not need to define these properties and behaviors, as long as they inherit that class.

Class inheritance can be implemented by extends keyword
    class 子类名 extends 父类名{}
Cases of inheritance
创建一个Person类,定义两个功能吃饭、睡觉,再创建学生类、教师类,继承Person类,再定义两个自己独有的功能创建Persen类public class Person {    public void eat(){        System.out.println("吃饭");    }    public void sleep(){        System.out.println("睡觉");    }}//创建子类学生类继承Person类public class Student extends Person {    public void play(){        System.out.println("打游戏");    }}//创建Teacher类继承Person类public class Teacher extends Person {    public void teach(){        System.out.println("教书");    }}//创建测试类,对继承进行测试public class PersonExtends {    public static void main(String[] args) {        Student st = new Student();        st.eat();   //用学生类调用继承方法        st.play();  //调用自己的方法        Teacher t =new Teacher();        t.sleep();        t.teach();    }}
Benefits of Inheritance
    • Improved reusability of code: the same members of multiple classes can be placed in a class

    • Improved code maintainability: If the code of the function needs to be modified, it can be changed in one place, and the inherited class will be modified automatically.

    • Having a relationship between classes and classes is a precondition for polymorphism

Inherited features in Java Java only supports single inheritance and does not support multiple inheritance

That is, a class can have only one direct parent class, and cannot have more than one direct parent class

    正确写法:class Sub extends Demo{}    错误写法:class Sub extends Demo1,Demo2{}
Java supports multilayer inheritance
    class A{}    class B extends A{}    class C extends B{}    例    //    public class Grandfather {        public void show(){            System.out.println("grandfather");        }    }    public class Father extends Grandfather {        public void method(){            System.out.println("father");        }    }    public class Son extends Father {        public void function(){            System.out.println("son");        }    }    //测试类    public class GrandfatherTest {        public static void main(String[] args) {            Son s = new Son();            s.function();            s.method();            s.show();        }    }
Considerations for Inheritance in Java
    1. Subclasses can inherit only all non-private members in the parent class (member variables, member methods)
    2. Subclasses cannot construct methods of the parent class, but can access the parent class construction method with the Super keyword
    3. Do not inherit for part of the function, if there are two classes A, B, only if they meet a is a or B is a one, you can consider the use of inheritance
Relationship of member variables in inheritance
案列演示://创建父类定义成员变量public class Field {    int num = 10;    public void method(){        System.out.println(num);    }}//创建子类继承父类,并定义与父类同名成员变量public class FieldExtends extends Field {    int num = 15;    public void show(){        System.out.println(num);    }    //在子类中定义新的方法,在方法内再定义与父类成员变量同名变量    public void function(){          int num = 5;        System.out.println(num);    }}//测试类public class FieldTest {    public static void main(String[] args) {        FieldExtends fe = new FieldExtends();        fe.show();  // 15        fe.function();   // 5        fe.method();   //10    }}
You can see the order in which a variable is accessed in a subclass by using the case column
    1. The local scope of the subclass method is searched, and there is the use
    2. In the subclass of the member scope to find, there is the use of
    3. Use if you have a parent class member scope
    4. If you can't find it, you get an error.
Super keyword

Usage is similar to the This keyword

    • This represents a reference to this class of objects
    • Super represents the identity of the parent storage space (which can be understood as a reference to the parent class object)
Usage
    • Accessing member variables

      this.成员变量super.成员变量(访问父类的成员变量,不能访问父类的private变量)访问静态成员时,也可以用  父类名.静态成员
    • Access Construction Methods

      this(...)  super(...)
    • Accessing member methods

      this.成员方法()  super.成员方法()
Case-Listing Demo
 //Create parent public class Fathersuper {int num = 10;        Public Fathersuper () {System.out.println ("Parent class constructor method");        public void Show () {System.out.println ("Parent class member method");        }} public class Sonsuper extends fathersuper {int num = 15;        Public Sonsuper () {System.out.println ("subclass constructor Method");        } public void Method () {System.out.println ("Subclass member Method");                                } public void function () {int num = 5;        SYSTEM.OUT.PRINTLN (num);  Local variable System.out.println (super.num) in the printing method;   Print the parent class member variable System.out.println (this.num);                   Print this class member variable super.show ();                  Call the parent class member Method This.method (); Call this class member method}} test class public class SuperTest {public static void main (string[] args) {Son            Super ss = new Sonsuper ();        Ss.function (); }    }
Relationship of construction methods in inheritance
    1. All constructor methods in a subclass access the constructor of the parent's hollow parameter by default, unless the display uses Super/this to invoke the parent class or other constructor methods of this class.
    2. A call to construct a method in a class or a parent class can only be constructed in a constructor method, and cannot be called in the Total instance method (more cannot be called in a class method)
Note Construction methods cannot be called recursively
    class A {        public A(int i){            this(1 ,2);        }        public A(int a ,int b){            this(2);        }    }
Case Demo
    //创建父类    public class A {        public A(){            System.out.println("父类空参构造");        }        public A(String name){            System.out.println("父类有参构造");        }    }    //创建子类继承父类      public class B extends A {        public B(){           //这一步默认执行了  super();调用了父类空参            System.out.println("子类空参构造");        }        public B(String name){            super(name);  //调用父类有参构造方法            System.out.println("子类有参构造");        }    }    测试类    public class C {        public static void main(String[] args) {            B b = new B();            B b1 = new B("tom");        }     }   
If the parent class does not have an empty parameter construct, the subclass's constructor must explicitly call the parent class with the parameter construct super (...); Super (...) Or this (...) Must appear on the first statement of the constructor method otherwise, there will be multiple initialization method overrides for the parent class data

A method declaration in a subclass that appears in the same way as a parent class, called a method override (override) or override (OverWrite)

Usage Features
    • Call the corresponding method if the method name is different
    • If the method name is the same as the end use of its own (when using the subclass reference, in polymorphic cases, using the parent class reference, it is possible to call the parent class static method)
Application of method overrides
    • When a subclass needs a parent class feature, and the feature body subclass has its own unique content, you can override the parent class's method, which inherits the functionality of the parent class and defines the unique content.
    • Method overrides are a condition of a polymorphic implementation

      //首先创建 一个手机父类public class PhoneF {    public void call(String name){   //定义一个方法        System.out.println("给"+name+"打电话");    }}//在创建一个手机子类继承父类public class PhoneS extends PhoneF {    public void call(String name){   //同名同修饰词   对父类中的方法进行重写        super.call(name);        System.out.println("听天气预报");  //在继承父类之后在身再加的打印语句    }}//创建测试类public class PhoneTest {    public static void main(String[] args) {        PhoneS ps = new PhoneS();        ps.call("Tom");    }}
Considerations for method overrides
    • The private method in the parent class cannot be overridden, compiling an error;
    • The subclass overrides the parent class method, the access permission cannot be lower, compiles the error;
    • When a subclass overrides a parent class method, the return value type can be the same, or it can be a subtype of the return value of the parent class;
    • Instance methods of the parent class (non-static methods), subclasses cannot be redefined as static methods
    • Overriding the parent class method in the subclass, according to the overriding principle (access permissions cannot be smaller, the return value type is homogeneous or subclass, the method name is the same, the formal parameter list is the same);
    • Subclasses want to rewrite the method of the parent class, it is best to make the signature of the method identical;
Final keyword

The final keyword is the ultimate meaning that can be decorated with classes, member variables, member methods-decorated classes, classes cannot be inherited (cannot be placed behind extends)-modifier variables, variables will become constants can only be assigned once, whether in the subclass or in this class, cannot be modified (constants are generally uppercase expressions final int one = 1)-modification method, method cannot be overridden (subclass with use rights only, no modification right)

Final modifier local variable
    • Within a method, the variable cannot be changed
    • On a method declaration, the base type is that the value of this parameter cannot be changed, the reference type, and the address value that this parameter only wants cannot be changed
Summarize

Non-static class final variables (instance final variables) can be assigned at the time of life, if the declaration is not assigned, it must be assigned in the following two places, one is to construct a code block is a construction method, if these two places are not assigned, compile an error.

If it is a static modified final variable, it can only be assigned in two places, when declared, or in a static block of code.

Polymorphic (polymorphism) a thing, a different state of being manifested at different times.

In Java, a reference to a thing can be divided into two types: a compile-time type and a run-time type. The compile-time type refers to the type specified when the variable is declared, and the run-time type refers to the type of the object that is actually assigned to the variable.

    若Student类继承自Person类,则下面的写法是正确的    Person p = new Student();
Attention

A parent class reference cannot call a method that is unique to a subclass, because a reference to the parent class is used to refer to the current subclass object from the parent class perspective, only to see attributes inherited from the parent class, or to be overridden by subclasses of the parent class. Member variables are not polymorphic and can only see member variables of the parent class.

feature of member access in polymorphic
    • Member variables compiled look to the left, run to the right;
    • When constructing a subclass object, access the constructor of the parent class to initialize the data of the parent class.
    • Member method Cheap look left, run look right
    • static method Compile look left, run look right
Prerequisites for polymorphic conditions
    • Have an inheritance relationship
    • There are methods to rewrite
    • There are parent class references to child class objects
member access characteristics in polymorphic

member variables and static methods are not polymorphic only the member methods overridden by the quilt class are polymorphic

Day 08Java Basic Learning Notes

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.