验证static的作用并重写toString方法
来源:互联网 发布:淘宝店logo尺寸大小 编辑:程序博客网 时间:2024/04/29 08:12
Java中用static定义静态变量,
相当于C++中的const,
用static定义的变量在多个类对象中始终保持与最后一次赋值一致。
上代码 ↓↓↓
在main函数中添加代码以验证类功能是否正常 ↓↓↓
程序运行结果请读者自行调试。
上述例子的运行结果可以看出,
最后student1与student2的学号都是10002,
说明两者的ID是一样的,并且以后一次赋值为准,
这就是static的作用。
读者可以去除 static int id; 中的static,
然后再次运行结果,
比较两次运行的不同之处。
相当于C++中的const,
用static定义的变量在多个类对象中始终保持与最后一次赋值一致。
上代码 ↓↓↓
public class Student { static int id; //定义一个静态的学生ID String name; //定义一个学生姓名 public String toString() //重写toString方法 { String str=id+" "+name; return str; //此时返回的是学生"ID 姓名"这样的一个字符串 }//toString方法}//Student类
在main函数中添加代码以验证类功能是否正常 ↓↓↓
public static void main(String[] args) { Student student1=new Student(); Student student2=new Student(); student1.id=10001; student1.name="张三"; student2.id=10002; student2.name="李四"; System.out.println(student1); System.out.println(student2); }//main
程序运行结果请读者自行调试。
上述例子的运行结果可以看出,
最后student1与student2的学号都是10002,
说明两者的ID是一样的,并且以后一次赋值为准,
这就是static的作用。
读者可以去除 static int id; 中的static,
然后再次运行结果,
比较两次运行的不同之处。
0 0
- 验证static的作用并重写toString方法
- java:继承并重写的方法
- JAVA中tostring方法的作用
- JAVA中toString方法的作用
- Java中重载toString()方法的作用
- JAVA中toString方法的作用
- JAVA中toString方法的作用
- JAVA中toString方法的作用
- JAVA中toString方法的作用
- JAVA中toString方法的作用
- equal(),hashcode(),toString()方法的作用
- JAVA中toString方法的作用
- JAVA中toString方法的作用
- JAVA中tostring方法的作用
- JAVA中toString方法的作用
- equal(),hashcode(),toString()方法的作用
- 浅析JAVA中toString方法的作用
- 浅析JAVA中toString方法的作用
- Microsoft Offcie2010打开office 2003 .doc扩展名的文件,会卡一点时间的解决办法
- 第10周项目程序填充与阅读
- 第十周项目一程序填充
- 文件下载工具类
- Using UIPageControl as a container UIViewController
- 验证static的作用并重写toString方法
- ubuntu安装Nginx
- android settings源代码分析(3)
- HttpEntity的类型及其使用
- LINUX netlink机制
- 昆仑叶哲华:刘备和当下创业者们的五点相似
- Enterprise Architect使用相关链接
- 浅谈服务程序的编写
- Android抽象布局——include、merge 、ViewStub