当前位置:网站首页>构造方法,this关键字,方法的重载,局部变量与成员变量
构造方法,this关键字,方法的重载,局部变量与成员变量
2022-08-02 00:04:00 【弱冠初心】
1.构造方法的作用:初始化对象
特点:1),无返回值 2),方法名和类名相同 3),可以指定参数
访问修饰符 构造方法名 ( ) {
//初始化代码
}
2.this 关键字的用法:
1),调用属性
this.name = "大黄"
2),调用方法
this.print();
3),调用构造方法:如果使用,必须放在构造方法的第一条语句
this();
this关键字可以用来区分
3.方法的重载:在同一个类中,出现多个方法的方法名相同,参数列表不同(参数的个数、参数的类型、参数顺序)的现象。
- 同一个类中
- 方法名相同
- 参数个数和类型不同
- 与返回值和访问修饰符无关
public class Sum {
//定义几个普通方法
public int sum(int num1,int num2){
return num1+num2;
}
public double sum(double num1,double num2){
return num1+num2;
}
public double sum(int num1,double num2){
return num1+num2;
}}
4.成员变量和局部变量
变量作用域:变量按照其所在的位置,可以分为成员变量(全局变量)、局部变量两大类
成员变量(类内方法外):
作用类中其它结构外的变量,
成员变量的作用范围是整个类中都可以使用(在静态方法中不能使用非静态的成员变量,可以使用静态的成员变量)
成员变量系统会给它赋值一个默认值
在同一个类中,不能有同名的全局变量,全局变量和局部变量可以同名,在使用的时候,局部变量具有更高的优先级
public class Demo01 {
String name;
int num1 = 1000;//成员变量
public void test(){
int num1;
System.out.println(name);
num1 = 100;
//局部变量在使用之前一定要赋值
System.out.println(num1);
}
局部变量(方法内):
作用方法中或者其它结构内的变量,
局部变量的作用范围只限于定义局部变量的结构中
局部变量没有默认值,在使用之前要进行赋值,否则会报错
在不同的方法内(获取其它结构内)可以有相同名称的局部变量,在同一个方法或者结构内不能有同名的局部变量
public class Demo01 {
String name;
int num1 = 1000;//成员变量
public void test(){
int num1;//方法内的局部变量
System.out.println(name);
num1 = 100;
//局部变量在使用之前一定要赋值
System.out.println(num1);
}
边栏推荐
- Interview high-frequency test questions solution - stack push and pop sequence, effective parentheses, reverse Polish expression evaluation
- 【21天学习挑战赛】顺序查找和二分查找的小总结
- Multi-feature fusion face detection based on attention mechanism
- After an incomplete recovery, the control file has been created or restored, the database must be opened with RESETLOGS, interpreting RESETLOGS.
- 一文概览最实用的 DeFi 工具
- JSP out.println()方法具有什么功能呢?
- Unknown CMake command “add_action_files“
- JSP out. The write () method has what function?
- 双队列实现栈?双栈实现队列?
- 【三子棋】C语言实现简易三子棋
猜你喜欢

security cross-domain configuration

短视频seo搜索优化主要内容

uni-app项目总结

OpenCV DNN blogFromImage() detailed explanation

Don't know about SynchronousQueue?So ArrayBlockingQueue and LinkedBlockingQueue don't and don't know?

Axure tutorial - the new base (small white strongly recommended!!!)

双队列实现栈?双栈实现队列?

磁盘与文件系统管理

玩转NFT夏季:这份工具宝典值得收藏

链上治理为何如此重要,波卡Gov 2.0又会如何引领链上治理的发展?
随机推荐
security CSRF漏洞保护
IP Core: FIFO
Axure教程-新手入门基础(小白强烈推荐!!!)
JSP out. The write () method has what function?
NFT工具合集
工业信息物理系统攻击检测增强模型
22.支持向量机—高斯核函数
短视频SEO搜索运营获客系统功能介绍
已知中序遍历数组和先序遍历数组,返回后序遗历数组
ROS dynamic parameters
06-SDRAM :SDRAM控制模块
After an incomplete recovery, the control file has been created or restored, the database must be opened with RESETLOGS, interpreting RESETLOGS.
How does JSP use the page command to make the JSP file support Chinese encoding?
JSP 如何获取request对象中的路径信息呢?
LeetCode_518_零钱兑换Ⅱ
07-SDRAM :FIFO控制模块
Double queue implementation stack?Dual stack implementation queue?
为什么要使用MQ消息中间件?这几个问题必须拿下
TCL:在Quartus中使用tcl脚本语言进行管脚约束
零基础如何学习单片机,一位入门者的进阶路径,可参考