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();
        }
    }

  • 相关阅读:
    在SharePoint 2010中,如何找回丢失的服务账号(Service Account)密码
    基于Picture Library创建的图片文档库中的上传多个文件功能(upload multiple files)报错怎么解决?
    使用PowerShell找出具体某个站点所使用的模板(Web Template)名称?
    多文档上传(upload multiple documents)功能不能使用怎么办?
    实验环境里新创建成功的web application却在浏览器中返回404错误
    SharePoint 2010中一些必须知道的限制
    Information Management Policy(信息管理策略)的使用范例
    Google云平台对于2014世界杯半决赛的预测,德国阿根廷胜!
    php 字符串分割输出
    php实现验证码(数字、字母、汉字)
  • 原文地址:https://www.cnblogs.com/chenyuan7/p/7967755.html
Copyright © 2011-2022 走看看