[Training Video - 3] [Java Introduction] [Object Oriented Programming]
Static and non-Static :
非静态方法(不带static)可以访问静态变量和方法(带static),但是反过来就不行。
类的静态成员(变量和方法)属于类本身,在类加载的时候就会分配内存,可以通过类名直接去访问。
非静态成员(变量和方法)属于类的对象,只有在类的对象产生(创建实例)的时候才会分配内存,然后通过类的对象去访问。
在一个类的静态成员中去访问非静态成员之所以会出错是因为在类的非静态成员不存在的时候静态成员就已经存在了,访问一个内存中不存在的东西会出错。
静态变量和方法既可以用类来调用,也可以用对象来调用,但不建议用对象调用
Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | public class Car { // GLOBAL VARIABLE String mod; int price; static int wheels = 4 ; // static functions can only access static stuff public static void main(String[] args) { Car c1 = new Car(); c1.mod = "Merc" ; c1.price = 8909809 ; c1.start(); c1.accel(); Car c2 = new Car(); c2.mod = "Maruti" ; c2.price = 8909809 ; c2.start(); c2.accel(); System.out.println(c1.mod); System.out.println(c2.mod); // static System.out.println(wheels); System.out.println(Car.wheels); c1.wheels = 8 ; System.out.println(wheels); System.out.println(Car.wheels); System.out.println(c2.wheels); fillGas( 100 ); Car.fillGas( 200 ); c1.fillGas( 900 ); } public void start(){ System.out.println(mod + " starting" ); } public void accel(){ System.out.println(mod + " acc" ); } public static void fillGas( int quantity){ } } |
Result :
1 2 3 4 5 6 7 8 9 10 11 | Merc starting Merc acc Maruti starting Maruti acc Merc Maruti 4 4 8 8 8 |
Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class Car { String mod; public static void main(String[] args) { Car a = new Car(); Car b = new Car(); Car c = new Car(); a.mod = "A" ; b.mod = "B" ; c.mod = "C" ; System.out.println(a.mod); System.out.println(b.mod); System.out.println(c.mod); a=b; b=c; c=a; System.out.println(a.mod); System.out.println(b.mod); System.out.println(c.mod); } } |
Result :
1 2 3 4 5 6 | A B C B C B |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2015-06-16 [Training Video - 6] [File Reading] [Java] Read Excel File Using Apache POI API
2015-06-16 [Training Video - 6] [File Reading] [Java] Read Properties file
2015-06-16 [Training Video - 6] [File Reading] [Groovy] Reading Properties file
2015-06-16 [Training Video - 5] [Groovy Script Test Step - Collections, Exceptions] HashSet and Hashtable
2015-06-16 [Training Video - 5] [Groovy Script Test Step - Collections, Exceptions] Array and ArrayList
2015-06-16 [Training Video - 4] [Groovy] String Functions
2015-06-16 [Training Video - 6] [File Reading] Making a Jar file with eclispe, Importing custom jars in SoapUI