当前位置:网站首页>构造方法,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);
}
边栏推荐
猜你喜欢

Axure tutorial - the new base (small white strongly recommended!!!)
![[Headline] Written test questions - minimum stack](/img/67/08f2be8afc780e3848371a1b5e04db.png)
[Headline] Written test questions - minimum stack

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

【解决】win10下emqx启动报错Unable to load emulator DLL、node.db_role = EMQX_NODE__DB_ROLE = core

SphereEx Miao Liyao: Database Mesh R&D Practice under Cloud Native Architecture

【三子棋】C语言实现简易三子棋

Collection of NFT tools

面试高频考题解法——栈的压入弹出序列、有效的括号、逆波兰表达式求值

GIF making - very simple one-click animation tool

08-SDRAM:汇总
随机推荐
好好活就是做有意义的事,有意义的事就是好好活
扑克牌问题
使用 Zadig 交付云原生微服务应用
Axure教程-新手入门基础(小白强烈推荐!!!)
How to solve the error when mysql8 installs make
【21天学习挑战赛】顺序查找和二分查找的小总结
Difference between JSP out.print() and out.write() methods
Play NFT summer: this collection of tools is worth collecting
不就是个TCC分布式事务,有那么难吗?
[Solution] Emqx startup under win10 reports Unable to load emulator DLL, node.db_role = EMQX_NODE__DB_ROLE = core
Axure tutorial - the new base (small white strongly recommended!!!)
如何发现新的潜力项目?工具推荐
JSP out.print()和out.write()方法的不同之处
以交易为生是一种什么体验?
一文概览最实用的 DeFi 工具
Simpson's paradox
信息物理系统状态估计与传感器攻击检测
GIF making - very simple one-click animation tool
JSP out.println()方法具有什么功能呢?
LeetCode_518_零钱兑换Ⅱ