修饰符之instancof,static静态的和静态导包

修饰符:instanceof和static

instanceof:判断左右对象是否为父子关系

多实践大脑中的想法

Person person = new Student();
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Teacher);//false

同等级间不可判断

  • Object --> Person
  • Object --> String
//System.out.println(person instanceof String);

向下造型:父类转型为子类(高到低)

//Student student = (Student)person;
((Student)person).learn();
//其余的代码:
package com.li.changGe.oop.instanceofDemo;

public class Person {
  public void see(){};
}
//----------------------------------------

package com.li.changGe.oop.instanceofDemo;

public class Student extends Person{
  public void see(){
    System.out.println("I'm a student.");
  }

  public void learn(){
    System.out.println("Student learning everyday");
  }

}
//----------------------------------------

package com.li.changGe.oop.instanceofDemo;

public class Teacher extends Person{
  public void see(){
    System.out.println("I'm a teacher.");
  }
}


static静态的

静态方法不可调用非静态成员:静态成员和类一起被加载

private static String name = "长歌";

public static void see(){
    System.out.println(name);
}

public static void main(String[] args) {
    see();
}

静态代码块(static成员只执行一次) > 代码块 > 构造方法

CodePiece codePiece = new CodePiece();
CodePiece codePiece1 = new CodePiece();
System.out.println(codePiece1.name);
代码块一般可以用来为属性赋初始值
class CodePiece{

    public String name;
    {
        System.out.println("I'm codePiece");
        this.name = "长歌";
    }

    static{
        System.out.println("I'm static codePiece");
    }

    public CodePiece(){
        System.out.println("I'm CodePiece's construction method");
    }

}

运行结果

在这里插入图片描述


静态导包

import static java.lang.Math.random;

public class StaticImportDemo01 /*extends StaticImport*/{
  public static void main(String[] args) {

    System.out.println(/*Math.*/random());
  }

}
final修饰的类为最终类,不可被继承
final class StaticImport{}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

helloses

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值