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

  • 相关阅读:
    java.net.DatagramPacket/java.net.DatagramSocket-UDP Socket编程
    新浪微博客户端(9)-实现版本新特性的ViewPager
    新浪微博客户端(8)-添加按钮到TabBar
    iOS-Auto property synthesis will not synthesize property 'delegate'; it will be implemented by its super
    新浪微博客户端(7)-通过转换坐标系来调整首页下拉菜单的位置
    新浪微博客户端(6)-创建首页下拉菜单
    TortoiseGit-创建分支、合并分支
    BZOJ2683: 简单题(cdq分治 树状数组)
    BZOJ3262: 陌上花开(cdq分治)
    BZOJ1901: Zju2112 Dynamic Rankings(整体二分 树状数组)
  • 原文地址:https://www.cnblogs.com/chenyuan7/p/7967755.html
Copyright © 2011-2022 走看看