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修饰变量,该变量一旦被赋值,其值不能被改变。

  • 相关阅读:
    Difference between Nested & Correlated Subqueries
    Oracle Btree、位图、全文索引三大索引性能比较及优缺点汇总(转载)
    subquery unnesting、Subquery unnesting and View Merge
    MySQL中如何定义外键[转]
    索引1
    创建索引和索引类型
    UpdatePanel的用法详解
    索引2
    [HTTP]GET 和POST的区别
    [转]解决silverlight引用中文字体的问题
  • 原文地址:https://www.cnblogs.com/miaowulj/p/14495352.html
Copyright © 2011-2022 走看看