三鑫西瓜霜

 

【java基础】面向对象&&变量

因为之前学过java对部分内容只做简单笔记,不是很详细。

  • 类的第一个字母大写
  • 类中可以调用自身
public class Hero {
    String name;
    float hp;
    float armor;
    int moveSpeed;

    void helpme(){
        System.out.println("救救我救救我!");
    }
    float heroHp(){
        return this.hp;
    }
    void reduceHp(float rhp){
        hp -= rhp;
    }
    public static void main(String[] args) {
        Hero timo = new Hero();
        timo.name = "提莫";
        timo.hp = 100;
        timo.armor = 50;
        timo.moveSpeed = 10;
        System.out.println("英雄名:"+timo.name);
        timo.reduceHp(99);
        timo.helpme();
        System.out.println(timo.heroHp());
    }
}

变量

  • Java的八种基本变量类型
  1. 整型
    1. byte     1字节
    2. short    2字节
    3. int        4字节
    4. long     8字节
  2. 字符型    char   2字节
  3. 浮点型
    1. float      4字节
    2. double   8字节
  4. 布尔型  boolen    1字节(1bit)
  5. String类型

字面值

  1. 以L或者l结尾的整数字面值是long类型
  2. 0x开头是16进制
  3. 0开头是8进制
  4. 0b开头是2进制
long val = 26L; //以L结尾的字面值表示long型
int decVal = 26; //默认就是int型
int hexVal = 0x1a; //16进制
int oxVal = 032; //8进制
int binVal = 0b11010; //2进制

以上都是26的不同进制字面值的赋值过程

float f1 = 123.4F;// 以F结尾的字面值表示float类型
double d1 = 123.4;// 默认就是double类型
double d2 = 1.234e2;// 科学计数法表示double

转义字符。不做详细说明了。

  1. Java中对float赋值小数时,一定加上F声明,否则会产生编译错误。
  2. 给byte或short变量进行赋值时,“=”右边如果是一个算术表达式,并且表达式中出现变量,肯定无法通过编译。
  3. 即使用常量给byte或short变量进行赋值,如果在“编译阶段”就能确定所赋的值已经超过了范围,同样会报错。
  •  类型转换

因为知识点和C++的基本一致,这里不做赘述

  • 命名规则

java的命名比C++多了一个字符$

离谱了!java变量竟然可以使用中文命名。

public class 英雄 {
    void 回应(){
        System.out.println("你好!");
    }

    public static void main(String[] args) {
        英雄 我 = new 英雄();
        我.回应();
    }
}

写代码时来回切换输入法很麻烦!及其不推荐。

  • 变量的作用域

分为三种:

  1. 字段、属性        (声明在类中)
  2. 参数                     (方法中的参数)
  3. 局部变量              (声明在方法中)
public class HelloWorld {
    int i = 1; //属性名是i
    public void method1(int i){ //参数也是i
        System.out.println(i);
        System.out.println(this.i);
    }

    public static void main(String[] args) {
        new HelloWorld().method1(5);
        //结果打印出来是 1还是5?
    }
}

可以通过this.i 来访问类的属性i

  • final修饰

当一个变量被final修饰时,该变量只有一次赋值的机会。

final修饰的类不能被继承

final定义的方法不能被重写

final定义的常量不能被重写赋值

public class HelloWorld {
    public void method1(int i){ //参数也是i
        System.out.println(i);
    }
    static {
        System.out.println("静态代码块");
        //this.method1(7);
    }
    {
        System.out.println("执行块");
        this.method1(5);
    }
    public static void main(String[] args) {
        new HelloWorld();
    }
}

静态代码块,就算不新建示例也将运行,可以输出一些辅助信息。

执行块,创建实例后会运行一次。同时其内部可以调用类中的方法和属性。

 

posted on 2021-10-13 11:17  三鑫西瓜霜  阅读(32)  评论(0)    收藏  举报

导航