zoukankan      html  css  js  c++  java
  • Java子类实例化函数复写对象转型

    一、子类实例化过程

      

    public class Student extends Person{
        /*
         * 继承父类成员和函数,不能继承构造函数
         * 在子类构造函数中,须调用父类的构造函数
         */
        Student(){
            super();//用于调用父类构造函数;若写则在第一条语句,若不写,编译器自动添加;可以调用父类有参构造函数super(..,..);
            System.out.println("student无参数构造函数");
        }
        public static void main(String agrc[]){
            Student s = new Student();
        }
    }
    class Person{
        int age;
        String name;
        Person(){
            
        }
        Person(int age, String name){
            this.age = age;
            this.name = name;
        }
    }

    二、函数的复写(override)

      也称之为覆盖或重写
      

    • 在具有父子关系的两个类中
    • 父类和子类中各有一个的函数,这两个函数的定义(返回值类型、函数名、参数列表)完全相同
    • 可以用(super.函数名)来调用父类的函数以减少重复代码

    三、对象的转型

    1. 向上转型:将子类的对象赋值给父类的引用(一定成功)
      • 一个引用能够调用哪些成员(变量、函数),取决于这个引用的对象。
      • 一个引用调用的是哪一个方法,取决于这个引用所指向的对象。
      • 如果子类复写方法,那么父类会使用这个复写的方法

      2.  向下转型:将父类的对象赋值给子类的引用(先向上转型然后转回来) 

    public class Student extends Person{
        int grade;
        void eat(){
            System.out.println("son");
        }
        public static void main(String agrc[]){
            /**************************************/
            //向上转型,也可以Person p1 = new Student();(学生是人)
            Student s1 = new Student();
            Person p1 = s1;
            //p1.grade = 5;出错,p能调用的成员根据p的类型Person中的成员来确定
            p1.eat();//输出son
            /**************************************/
            //向下转型,先向上转型再转回来;(学生是人,人再是学生)
            Person p2 = new Student();
            Student s2 = (Student)p2;
            //错误的转型(人是学生??!!)
            //Person p2 = new Person();
            //Student s2 = (Student)p2;
        }
    }
    class Person{
        int age;
        String name;
        void eat(){
            System.out.println("father");
        }
    }
  • 相关阅读:
    mysql重置id
    mysql数据类型
    手把手教你新建一个Vue项目
    用markdown开始优雅的写作
    源码阅读心得
    断点调试-程序员的必修课
    代码还是短点好!
    GoJS v1.8.27 去水印方法
    VS code不用集成终端如何修改并推送分支?
    LeetCode日拱一卒
  • 原文地址:https://www.cnblogs.com/qiu520/p/4099011.html
Copyright © 2011-2022 走看看