zoukankan      html  css  js  c++  java
  • super关键字和final关键字的用法

    一.super关键字的用法

    super关键字用于继承关系中,子类访问父类的成员变量、成员方法和构造方法

    1.1 使用super关键字调用父类的成员变量和成员方法

    dog类继承与Animal,在dog类中重写shout方法,通过super.shout()访问父类Animal类中的shout方法,通过super.name访问Animal类中的name属性

    package com.blog;
    
    //定义Animal类
    class Animal{
        String name = "动物";
        //定义动物叫的方法
        void shout(){
            System.out.println("动物发出叫声");
        }
    }
    
    //定义Dog类继承Animal类
    class Dog extends Animal{
        String name = "犬类";
        //重写父类的shout方法
        void shout(){
            super.shout();
        }
        //定义打印name的方法
        void printName(){
            System.out.println("name = " + super.name);
        }
    }
    
    public class SuperTest {
        public static void main(String[] args) {
            Dog dog = new Dog();
            dog.shout();
            dog.printName();
        }
    }
    

    output:

    1.2 使用super关键字调用父类的构造方法

    继承关系中,子类构造方法通过super(options:[参数1],[参数2])调用父类的构造方法

    //定义Animal类
    class Animal{
        //定义Animal的构造方法
        public Animal(String name){
            System.out.println("我是一只" + name);
        }
    }
    
    //定义Dog类继承Animal类
    class Dog extends Animal{
        public Dog(){
            super("沙皮狗");
        }
    }
    
    public class SuperStructMethod {
        public static void main(String[] args) {
            new Dog();
        }
    }
    

    Output:子类Dog构造方法中super("name")调用了父类的构造方法

    二.final关键字的用法

    ● final关键字修饰类,该类不能被继承。
    ● final关键字修饰方法,这个类的子类将不能重写该方法。
    ● final修饰变量,该变量一旦被赋值,其值不能被改变。

  • 相关阅读:
    python学习笔记:遍历目录
    c++笔记:友元函数
    VMware Workstation 9: This virtual machine's policies are too old to be run by this version of VMware
    inet_ntoa内存问题
    python学习笔记:sqlite3查询
    python学习笔记:利用asyncore的端口映射(端口转发)
    编写谷歌浏览器的油猴脚本
    window编译7z
    通过配置nginx的header路由到不同环境的服务器
    用U盘给物理机安装ubuntu20.04
  • 原文地址:https://www.cnblogs.com/miaowulj/p/14495352.html
Copyright © 2011-2022 走看看