this,继承,super

this的用法:

1.当成员变量与局部变量同名时,使用this指定成员变量。

2.使用this在构造方法的第一行掉用构造方法的功能。

this();调用的是本类的无参构造

this(参数);调用的是本类对应参数的构造方法

public class TestThis2 {
    public static void main(String[] args) {
        Dog d1  =  new Dog();
//        Dog d2  =  new Dog("旺财");
    }
}
//1.创建小狗类
class Dog{
    public Dog() {
        /**
         * 在无参构造中,调用含参构造的功能
         * 注意:调用是单向的,不能来回双向调用,否则会死循环
         */
        this("小旺旺");
        System.out.println("无参构造函数");
    }

    public Dog(String s) {
        /* 在含参构造中,调用无参构造的功能 */
//        this();   //调用无参构造函数的功能,规定:this关键字必须在构造函数的第一行
        System.out.println("含参构造"+s);
    }

含参构造小旺旺
无参构造函数

this()

调用构造函数,并且放在一个构造函数的第一个,不能双向调用。

public class TestThis1 {
    public static void main(String[] args) {
    Cat c= new Cat();
    c.eat();
    }
}
class Cat{
    int count=666;
    int sum=100;
    public  void eat(){
        int sum=10;//创建局部变量
        System.out.println(sum); //使用的是局部变量,就近原则
        System.out.println(this.sum);//当成员变量与局部变量同名时,可以使用this指定本类的成员变量
        System.out.println(count);
    }
}


10
666

继承格式:子类 extends 父类

java只支持单继承,一个子类只能有一个父类,但是一个父类可以有多个子类。

继承相当于是子类将父类的功能的复制了一份

继承还具有传递性,爷爷的功能会传给爸爸,爸爸的功能会传给孙子

子类可以拥有自己独有的方法,实现了功能的拓展,青出于蓝而胜于蓝

子类继承了父类以后,可以使用父类的所有非私有资源

注意:这个私有资源由于被private修饰,所有没有访问权限

继承是is a的关系,比如小猫是小动物,MiaoMiao是一只小猫

继承要求子类必须是父类的一种下属类型,依赖性非常强,强藕合。

super用法:

1.当父类的成员变量与子类的变量同名时,使用super指定父类的成员变量

子类在创建对象时,默认会先调用父类的构造方法

2* 原因是子类构造函数中的第一行默认存在super();----表示调用父类的无参构造

3* 当父类没有无参构造时,可以通过super(参数)调用父类的其他含参构造

4* 子类必须调用一个父类的构造函数,不管是无参还是含参,选一个即可。

5. 构造方法不可以被继承,因为语法的原因,要求构造方法的类名必须是本类类名,不能在子类中出现父类名字的构造方法。

package cn.teda.oop2;

public class ExtendsDemo1 {
    public static void main(String[] args) {
        new Son().study();
    }
}
class Father{
   int sum=1;
   int count=2;
}
class Son extends Father{
   int sum=10;
   public void study(){
       System.out.println("good good study,day day up");
       int sum=100;
       System.out.println(sum);
       System.out.println(this.sum);
       /**
        * 当父类的成员变量与子类的成员变量同名时,可以使用super指定父类的成员变量
        * 我们可以把super看作是父类的对象:Father super=new Father();
        */
       System.out.println(super.sum);
   }
}

good good study,day day up
100
10
1
/**
 * 子类在创建对象时,默认会先调用父类的构造方法
 * 原因是子类构造函数中的第一行默认存在super();----表示调用父类的无参构造
 * 当父类没有无参构造时,可以通过super(参数)调用父类的其他含参构造
 * 子类必须调用一个父类的构造函数,不管是无参还是含参,选一个即可。
 */
public class ExtendsDemo2 {
    public static void main(String[] args) {
//        Father2 f=new Father2();
//        Father2 f2=new Father2("哈哈哈");
           Son2 s1=new Son2();
    }
}
class Father2{
//    public Father2() {
//        System.out.println("我是父类的无参构造");
//    }
    public Father2(String s) {
        System.out.println("我是父类的含参构造"+s);
    }
}
class Son2 extends Father2{
    public Son2() {
        super("您好");  //调用父类的无参构造
    System.out.println("我是子类的无参构造");
   }

}

我是父类的含参构造您好
我是子类的无参构造

猜你喜欢

转载自blog.csdn.net/weixin_43762083/article/details/120743129