zoukankan      html  css  js  c++  java
  • Java super关键字

    super:在对象内部使用,可代表父类对象

    1.访问父类的属性:super.属性;

    例:

    class Animal{
        public String name;
        public int age=11;
        public void eat(){
            System.out.println("动物有吃东西的能力");
        }
        public Animal(){
            System.out.println("Animal类执行了");
        }
    }

    class Dog extends Animal{
        public int age=20;
        public void eat(){
            System.out.println("狗有吃骨头的能力");
        }

     public Dog(){
            System.out.println("Dog类执行了");
        }

       public void method(){

            System.out.println(this.age);    //本类

      //若想得到父类的属性        //若想得到子类的属性值

            System.out.println(super.age);    //则:System.out.println(age);

      //若想得到父类的方法        //若想得到子类的方法

             //super.eat();            //则:eat();

        }

    }

    class Ex17{

           public static void main(String[] args){

                 Dog dog=new Dog();

                 //在main调用method方法

                dog.method();

          }

    }

    2.访问父类的方法:super.方法();

    子类的构造的过程当中必须调用其父类的构造方法

    class Animal{
        public int age=10;
        public String name;
        public void eat(){
            System.out.println("动物有吃东西的能力");
        }
    public Animal(){
            System.out.println("Animal类执行了");
        }
    }
    class Dog extends Animal{
    public void eat(){
        String name="二哈";
        System.out.println(name+"有吃骨头的能力,它今年"+age+"岁");
    }
    public Dog(){
    System.out.println("Dog类构造方法执行了");
    }
    }
    class Ex11{
    public static void main(String[] args){
    Dog dog=new Dog();
    dog.eat();
    }
    }

    • 如果子类的构造方法中没有显示调用父类的构造方法,则系统默认调用父类无参的构造方法(用super)
    • 如果显示的调用构造方法,必须在子类的构造方法的第一行
    • 如果子类构造方法中既没有显示调用父类的构造方法,而父类又没有无参的构造方法,则系统会报错

    class Animal{
        public int age=10;
        public String name;
        public void eat(){
            System.out.println("动物有吃东西的能力");
        }
        public Animal(){
            System.out.println("Animal类执行了");
        }
    }
    class Dog extends Animal{
        public void eat(){
            System.out.println("狗有吃骨头的能力");
        }
        public Dog(){
            System.out.println("Dog类构造方法执行了");
        }
    }
    class HelloWorld{
        public static void main(String[] args){
            Dog dog=new Dog();
            dog.eat();
        }
    }

  • 相关阅读:
    Linux面试题汇总答案
    VMWARE ESXI 虚拟硬盘的格式:精简置备、厚置备延迟置零、厚置备置零
    [Python基础知识]正则
    [代码评审1]代码评审
    [EF2]Sneak Preview: Persistence Ignorance and POCO in Entity Framework 4.0
    [EF1]POCOs(Plain Old C# Object)Entity Framework 4.x: POCOs入门
    [网站性能3]SqlServer中Profiler的使用
    [网站性能2]Asp.net平台下网站性能调优的实战方案
    [网站性能1]对.net系统架构改造的一点经验和教训
    2.1 python使用MongoDB 示例代码
  • 原文地址:https://www.cnblogs.com/chenyuan7/p/7967755.html
Copyright © 2011-2022 走看看