当前位置:网站首页>Polymorphic day02

Polymorphic day02

2022-07-06 03:03:00 Dachang whole stack

/*
 
        // Not polymorphism     Student stu = new Student(); 
        // It's polymorphism       Person p = new Student(); 
    3. The premise of polymorphism :
        (1) There must be inheritance or interface implementation 
        (2) There must be a parent class reference to a child class object ( Variables of the parent type store the address value of the subclass object )
        (3) There must be a method override , Otherwise, the meaning of polymorphism will be lost 
   p = new Teacher(); 
 Found in parent class :  No, kanHome Method definition , Compiler error 
    4. The nature of polymorphism 
        (1) Is to use the subclass object as the parent type     The parent class reference points to the subclass object ( Variables of the parent type store the address value of the subclass object ) 
        (2) Call methods in a polymorphic way , Method follows the object 
*/ 
// The disadvantage of not using polymorphism :  Very poor scalability 
//dog = new Cat();// error :  Type mismatch 

// Disadvantages of using polymorphism :  You cannot call the specific behavior of a subclass 
//a.kanHome();
 The upward transformation in polymorphism -- Automatic type conversion 
       
    Downward transformation in polymorphism = Cast 
        Data or variables with a large value range cannot be directly assigned to variables with a small value range 
       double d2 = 100;//double:  Occupy 8 Bytes 
       int c = (int)d2;//int:  Occupy 4 Bytes 
        Cast :
            Post transfer type   Object name  = ( Post transfer type ) Name of the object or variable before conversion ;
 Be careful : many 
     The downward transformation of state ( Cast ) There are safety risks 
        If the type before conversion is inconsistent with the type after conversion , The type conversion exception will be reported (ClassCastException)
     
// Move down :  Use subclass objects as subclass types 
Dog dog = (Dog) a;

// Call specific methods 
dog.kanHome();
/*
     Cast ( Move down ) There are safety risks :
         If the post conversion type is inconsistent with the specific type of the created object , Report type conversion exception  ClassCastException 
     How to solve it ?
         If the variable a Pointing to Dog type , hold Animal Variable of type a Cast to Dog type 
         If the variable a Pointing to Cat type , hold Animal Variable of type b Cast to Cat type 

     How to judge variables a What kind of object is it pointing to ?
         Use instanceof keyword 
         Use format :
            boolean result =  Object name  instanceof  Class name 
                 If the object of this class is saved in the object name , return true.
                 If the object of this class is not saved in the object name , return false.
*/
package com.itheima;
/*
     Polymorphic usage scenarios 
         Use the parent type / Interface type as method parameter ,
         When calling a method , Subclasses can be passed / Implementation class object 
 */
public class Demo10DuoTai {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
        showAnimal(dog);
        showAnimal(cat);
    }
    /*
          problem :
              Use specific subclasses as method parameters ,
              How many subcategories , How many methods must be defined 
          solve :
              Use the parent type as the method parameter , Can receive all subclass objects 
      */
    // Define methods , Use Animal Class as parameter 
    //Animal Is an abstract parent class , Subclass objects must be passed 
    public static void showAnimal(Animal a) {
        // Calling method 
        a.eat();
        a.sleep();
        // Judge the reference variable a Is saved in Dog Class object , If it is Dog Class object instanceof return true
        if (a instanceof Dog) {
            // Move down :  Use subclass objects as subclass types 
            // Put the reference variable a Memory address in , Cast the type to Dog type , Assigned to the left Dog Variable dog
            Dog dog = (Dog) a;
            // Call specific methods 
            dog.kanHome();
        }

        // Judge the reference variable a Is saved in Cat Class object , If it is Cat Class object instanceof return true
        if (a instanceof Cat) {
            // Move down :  Use subclass objects as subclass types 
            // Put the reference variable a Memory address in , Cast the type to Cat type , Assigned to the left Cat Variable cat
            Cat cat = (Cat)a;
            // Call specific methods 
            cat.catchMouse();
        }
    }
}
2. Define notebook Computer class 
     Member method :  Boot function , Shutdown function , Use USB Function of interface 
    computer.useUSB(mouse);
    // The notebook Computer Class object calls use USB Interface functions :  Pass external device keyboard KeyBoard Class object 
    computer.useUSB(keyBoard); 
// Method parameters are interfaces :  When calling a method, you must pass the interface implementation class object 
// Method is called : USB usb = 0x666 = new Mouse()  polymorphic ( On the left is the interface variable , On the right is the implementation class object )
/*
    final keyword :  Represents the final , It can't be changed 
         What can be modified :
        1. class :
             Can't be inherited , Cannot have subclasses 
             see : MyString and MyArrayList
             Call them eunuchs :  There can be no subclasses , But there are parent classes 
        2. Method :
             Cannot be overridden by subclasses 

        3. Variable :    Can only assign once , The second assignment is not allowed , The value of a variable cannot be changed       Constant 
        // error : Fu01 By final modification , Can't be inherited 
        public MyArrayList(Collection c) {   super(c); }
 */
/*
// By final The method of decoration :  Cannot be overridden by subclasses   
     Subclass rewritten method , You can add final
     Meaning :  The method function of subclasses has been very perfect , If there are grandchildren , It is not allowed to override this method 
 */
@Override
public /*final*/ void fun() {
    System.out.println("Zi02...fun...");
}
public class MyClass03 {
    String name;
    final int num;// Definition not initialized 
    final int num2 = 10;// Define and initialize 

    // Be careful :  The construction method is after the object is created ( At this point, the member variables of the object have values ) Executive 
    // Space parameter structure 
    public MyClass03() {
        // error :  You cannot assign a value a second time 
        //num2 = 100;
        // correct :  First assignment 
        num = 200;
    }

    // There are parametric structures 
    public MyClass03(String name,int num) {
        this.name = name;
        // correct :  First assignment 
        this.num = num;
        // error :  You cannot assign a value a second time 
        //num2 = 100;
    }

    // Member method :  Must be called by an object , We have all the objects , Member variables already have values 
    public void method() {
        // error :  You cannot assign a value a second time 
        //num2 = 100;
        // error :  You cannot assign a value a second time 
        //num = 2000;
    }
}
package com.itheima.d3_final_var;

import java.util.Arrays;

/*
    final Modifying variables :
        1. characteristic :  Can only assign once , The second assignment is not allowed , The value of a variable cannot be changed       Constant 
        2. Modify local variables ( Method ):
            (1) Basic types :  The specific number stored in the basic type variable cannot be changed 

            (2) Reference type :  Address value of the stored object , By final After modification , It indicates that the address value of the object stored in the variable cannot be changed 
                                 But the contents of the memory space represented by this address can be changed 

        3. Member variables :  see MyClass03  The default value is considered invalid , Or assign values explicitly , Or the assignment in the constructor 
            (1) Definition unassigned : -- see MyClass03 Medium num
                 Of all construction methods , Must complete the right final Assignment of modified variables 
                 Of all member methods , Do not modify final The value of the decorated variable 

            (2) Define and assign : -- see MyClass03 Medium num2
                 All construction methods / In the member method , Do not modify final The value of the decorated variable 
 */
public class Demo03FinalVar {
    public static void main(String[] args) {
         
        //final Decorate reference types ( Array ) local variable 
        final int[] array = new int[]{10, 20};
        System.out.println(Arrays.toString(array));
        // Expand each element of the array 10 times 
        // error :  An array variable array By final After modification , Note that the memory address value saved internally cannot be changed 
        //array = new int[]{100, 200};
        for (int i = 0; i < array.length; i++) {
            // Just find the array through the original address , Modify element values , But the memory address value is not modified 
            array[i] *= 10;
        }
        System.out.println(Arrays.toString(array));
        System.out.println("----------------");

        //final Decorate reference types ( class ) local variable 
        final Student stu = new Student(" Zhang San ", 18);
        stu.show();
        // Two years later, , Age increases by two years 
        // error :  Reference variables stu By final After modification , Note that the memory address value saved internally cannot be changed 
        //stu = new Student(" Zhang San ", 20);
        // Just find the object by address , Change the value of the member variable , But the memory address value is not modified 
        stu.setAge(stu.getAge() + 2);
        stu.show();
    }

    public static void change(final int a, final int b) {
       /* a*=10;
        b*=10;*/
    }
}
// Define variables using four different permission modifiers 
public int a = 1;
protected int b = 11;
int c = 111;
private int d = 1111;
// Unrelated classes of different packages :  Only public have access to , The rest cannot be used 
// Different kinds of baozi :  except private And default 
// The same baozi :  except private Can be used outside 
/*
     Permission modifier                    public          protected            Default ( Write nothing )           private
     In the same class                    √                  √                   √                       √
     In the same package ( Subclass / Unrelated class )      √                  √                   √
     Subclasses of different packages                    √                  √
     Unrelated classes of different packages                  √
 */
原网站

版权声明
本文为[Dachang whole stack]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060257014631.html