Head First Java基础编程: 类与对象
程序员文章站
2022-06-27 16:12:34
类1.类是定义同一类所有对象的变量和方法的蓝图或原型。2.实例变量的值由类的每个实例提供。当创建类的实例时,就创建了这种类型的一个对象,然后系统为类定义的实例变量分配内存。然后可以调用对象的实例方法实现一些功能。3.除了实例变量和方法,类也可以定义类变量和类方法。类与对象类不是对象,却是用来创建对象的模型。类会告诉虚拟机如何创建某种类型的对象。main()的用途1.测试真正的类2.启动java程序猜数字游戏public class GuessGame { Player p1; Pl...
类
1.类是定义同一类所有对象的变量和方法的蓝图或原型。
2.实例变量的值由类的每个实例提供。当创建类的实例时,就创建了这种类型的一个对象,然后系统为类定义的实例变量分配内存。然后可以调用对象的实例方法实现一些功能。
3.除了实例变量和方法,类也可以定义类变量和类方法。
类与对象
类不是对象,却是用来创建对象的模型。类会告诉虚拟机如何创建某种类型的对象。
main()的用途
1.测试真正的类
2.启动java程序
猜数字游戏
public class GuessGame {
Player p1;
Player p2;
Player p3;
public void startGame() {
p1 = new Player();
p2 = new Player();
p3 = new Player();
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
int targetNumber = (int) (Math.random() * 10);
System.out.println("I'm thinking of a number between 0 and 9...");
while(true) {
System.out.println("Number to guess is " + targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1 = p1.number;
System.out.println("Player one guessed " + guessp1);
guessp2 = p2.number;
System.out.println("Player two guessed " + guessp2);
guessp3 = p3.number;
System.out.println("Player three guessed " + guessp3);
if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
if (p1isRight || p2isRight || p3isRight)
{
System.out.println("We have a winner!");
System.out.println("Player one got it right? " + p1isRight);
System.out.println("Player two got it right? " + p2isRight);
System.out.println("Player three got it right? " + p3isRight);
System.out.println("Game is over");
break;
}
else
{
System.out.println("Players will have to try again.");
}
}
}
}
public class Player {
int number = 0;
public void guess()
{
number = (int) (Math.random() * 10);
System.out.println("I'm guessing " + number);
}
}
public class GameLauncher {
public static void main (String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
Java会拾荒
Java会根据对象的大小分配内存空间,对象会被存放在称为堆得内存区域中。对象被虚拟机认定为不会再被使用时,会被标记为可回收的,垃圾使其就会将其回收。
本文地址:https://blog.csdn.net/weixin_44088692/article/details/109898067
上一篇: 万变不离其宗之反射原理篇