面向对象(六) 代码块

1.代码块

代码块,简单来讲,就是用“{}”括号括起来的一段代码,根据位置及声明关键字的不同,代码块可以分为4种:普通代码块、构造块、静态代码块、同步代码块。

普通代码块

public class Example12 { 
	public static void main(String[] args) {
	   {
         int age = 18;
         System.out.println("这是普通代码块。age:"+age);
        } 
         int age = 30;
         System.out.println("age:"+age);
	}
}

构造块

public class Student {
    String name;
    {
        System.out.println("我是构造代码块");
    }
    public Student(){
        System.out.println("我是Student的构造方法");
    }
}
public class Example12 {
    public static void main(String[] args) {
        Student stu1=new Student();
        Student stu2=new Student();

    }
}

静态代码块

在Java类中,用static关键字修饰的代码块称为静态代码块。当类被加载时,静态代码块会执行,由于类只加载一次,因此静态代码块只执行一次。在程序中,通常使用静态代码块对类的成员变量进行初始化。

public class Student {
    String name;
    {
        System.out.println("我是构造代码块");
    }
    static {
        System.out.println("我是静态代码块");
    }
    public  Student(){
        System.out.println("我是Student类的构造方法");
    }
}
public class Example16 {
    public static void main(String[] args) {
        Student stu1=new Student();
        Student stu2=new Student();
        Student stu3=new Student();
    }
}

从运行结果可以看出,代码块的执行顺序为静态代码块、构造代码块、构造方法。 static修饰的量会随着class文件一同加载,属于优先级最高的。在main()方法中创建了3个Student对象,但在3次实例化对象的过程中,静态代码块中的内容只输出了一次,这就说明静态代码块在类第一次使用时才会被加载,并且只会加载一次。

静态属性

如果在Java程序中使用static修饰属性,则该属性称为静态属性(也称全局属性),静态属性可以使用类名直接访问,访问格式如下:

类名.属性名

public class Student {
    String name;
    int age;
   static String school="A大学";

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void info(){
        System.out.println("姓名"+this.name+",年龄"+this.age+",学校"+school);
    }
}

public class Test {
    public static void main(String[] args) {
        Student stu1=new Student("张三",18);
        Student stu2=new Student("李四",19);
        Student stu3=new Student("王五",20);
        stu1.school="B大学";
        stu1.info();
        stu2.info();
        stu3.info();
    }
}

在运行结果中可以发现,只修改了一个stu1对象的学校属性,stu1和stu2对象的school属性内容都发生了变化,说明使用static声明的属性是对所有对象共享的。

静态方法

如果想要使用类中的成员方法,就需要先将这个类实例化,而在实际开发时,开发人员有时希望在不创建对象的情况下,通过类名就可以直接调用某个方法,要实现这样的效果,只需要在成员方法前加上static关键字,使用static关键字修饰的方法通常称为静态方法。

同静态变量一样,静态方法也可以通过类名和对象访问,具体如下所示

类名.方法

实例对象名.方法

使用示例

public class Student {
    private String name;
    private int age;
    private  static  String school="A大学";

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static String getSchool() {
        return school;
    }

    public static void setSchool(String school) {
        Student.school = school;
    }
    public void info(){
        System.out.println("姓名"+this.name+",年龄"+this.age+",学校"+school);
    }
}
public class Example15 {
    public static void main(String[] args) {
        Student stu1=new Student("张三",18);
       Student stu2=new Student("李四",19);
        Student stu3=new Student("王五",20);
    stu1.setAge(20);
    stu2.setName("小明");
    Student.setSchool("b大学");
    stu1.info();
    stu2.info();
    stu3.info();
    }

}

ps:静态方法只能访问静态成员,因为非静态成员需要先创建对象才能访问,即随着对象的创建,非静态成员才会分配内存。而静态方法在被调用时可以不创建任何对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是一个简单的使用面向对象思想实现的扫雷小游戏的代码示例: ```python import random class Square: def __init__(self, x, y): self.x = x self.y = y self.is_clicked = False self.has_mine = False self.adj_mine_count = 0 def set_mine(self): self.has_mine = True def set_adj_mine_count(self, count): self.adj_mine_count = count def click(self): self.is_clicked = True def __str__(self): if self.is_clicked: if self.has_mine: return '*' else: return str(self.adj_mine_count) else: return '.' class Board: def __init__(self, width, height, num_mines): self.width = width self.height = height self.num_mines = num_mines self.grid = [[Square(x, y) for y in range(height)] for x in range(width)] self.generate_mines() def generate_mines(self): for i in range(self.num_mines): x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) square = self.grid[x][y] while square.has_mine: x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) square = self.grid[x][y] square.set_mine() for adj_square in self.get_adj_squares(square): adj_square.set_adj_mine_count(adj_square.adj_mine_count + 1) def get_adj_squares(self, square): adj_squares = [] for x in range(square.x - 1, square.x + 2): for y in range(square.y - 1, square.y + 2): if x >= 0 and x < self.width and y >= 0 and y < self.height and not (x == square.x and y == square.y): adj_squares.append(self.grid[x][y]) return adj_squares def click_square(self, x, y): square = self.grid[x][y] square.click() if square.has_mine: return False if square.adj_mine_count == 0: for adj_square in self.get_adj_squares(square): if not adj_square.is_clicked: self.click_square(adj_square.x, adj_square.y) return True def is_game_over(self): for x in range(self.width): for y in range(self.height): square = self.grid[x][y] if not square.is_clicked and not square.has_mine: return False return True def __str__(self): return '\n'.join([''.join([str(self.grid[x][y]) for y in range(self.height)]) for x in range(self.width)]) class Game: def __init__(self, width, height, num_mines): self.board = Board(width, height, num_mines) self.game_over = False self.num_mines = num_mines def play(self): while not self.game_over: print(self.board) x = int(input("Enter x coordinate: ")) y = int(input("Enter y coordinate: ")) if not self.board.click_square(x, y): self.game_over = True print("Game over! You clicked on a mine.") elif self.board.is_game_over(): self.game_over = True print("Congratulations! You have cleared all the squares without clicking on a mine.") else: print("Remaining mines: ", self.num_mines - self.count_mines_clicked()) def count_mines_clicked(self): count = 0 for x in range(self.board.width): for y in range(self.board.height): square = self.board.grid[x][y] if square.has_mine and square.is_clicked: count += 1 return count if __name__ == '__main__': game = Game(8, 8, 10) game.play() ``` 这个代码实现了一个简单的扫雷游戏,使用了面向对象的思想,将方块和游戏板都抽象成了对象,方便维护和拓展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

浩气长存在心中

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

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

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

打赏作者

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

抵扣说明:

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

余额充值