继承的知识点

来源:互联网 发布:夏普55寸电视 知乎 编辑:程序博客网 时间:2024/06/06 03:07

在学习抽象和封装后我们学习了继承。

继承:就是把子类共有的东西提取到父类当中,然后子类运用关键字extends继承父类中的共有属性和方法。

   继承的语法:修饰符 class 子类类名 extends 父类类名{  }

    在继承中我们要注意继承中不能被继承的内容有:

         ① 类的构造方法不能被继承(父类不是无参构造方法,子类不能继承)。

         ②虽然不能继承构造方法,但是我们可以在子类的构造方法中用super来调用父类的构造方法。

         ③私有的属性(成员变量)不能被继承(子类不能继承private修饰的成员变量和方法)。 

         ④如果子类跟父类不在同一个包中,private修饰的属性和方法也是可以被继承下来的。

         类的构造方法不能被继承的例子。

        例子:class Test 
                   {
                   public static void main(String[] args) 
                  {

                          }

                   } 

                   class Pet{

                        private String name;

                        private int  health;

                        private int love;

                        public Pet(String name, int health, int love){
                  this.name = name;
                  this.health = health;
                  this.love = love;

                        public void setName(String name){
               this.name = name;
                }
                public void setHealth(int health){
                this.health = health;
                }
                public void setLove(int love){
                this.love = love;
                }
                public String getName(){
                return name;
                }
                public int getHealth(){
                return health;
                }
                        public int getLove(){
               return love;
                 }

                        public void print(){

                              System.out.println("亲爱的主人,你好,我的名字是:" + name + ", 我的健康值是:" + health + ", 我们的亲密度是:" + love);

                         }

}

                  //狗类继承宠物类里共有的属性

                  class dog estends Pet{

                        public void playBall(){
                System.out.println("叫" + name + "的狗在玩球");
                }

                   }

         class Test{

                Pet p = new Pet("宠物", 100, 50);
p.print();

                /*

                再这里构造方法是不能被构成的

                如果我们自定义了 父类的构造方法, 那么父类的 无参构造方法 会被收回
当子类在 调用无参构造方法 new对象的时候, 如果父类中没有找到 无参构造方法
程序出现运行时错误:
java.lang.NoSuchMethod: Pet: method <init><>U not found

                Dog jack = new Dog("宠物", 100, 50);
jack.print();

                 */

         }

0 0
原创粉丝点击