当前位置:网站首页>构造方法,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);
}
边栏推荐
- When Netflix's NFTs Forget Web2 Business Security
- NFT工具合集
- 磁盘与文件系统管理
- 【解决】win10下emqx启动报错Unable to load emulator DLL、node.db_role = EMQX_NODE__DB_ROLE = core
- Multi-feature fusion face detection based on attention mechanism
- 认识USB、Type-C、闪电、雷电接口
- 2022/08/01 学习笔记 (day21) 泛型和枚举
- 如何优雅的消除系统重复代码
- How to reinstall Win11?One-click method to reinstall Win11
- ROS dynamic parameters
猜你喜欢
面试必问的HashCode技术内幕
【三子棋】C语言实现简易三子棋
Unknown CMake command “add_action_files“
扑克牌问题
PHP从txt文件中读取数据的方法
REST会消失吗?事件驱动架构如何搭建?
Axure tutorial - the new base (small white strongly recommended!!!)
Disk and file system management
Win11内存管理错误怎么办?
Detailed explanation of Zadig's self-testing and tuning environment technical solution for developers
随机推荐
els strip deformation
Arduino Basic Syntax
LeetCode_279_完全平方数
How does JSP use request to get the real IP of the current visitor?
How to reinstall Win11?One-click method to reinstall Win11
els 方块变形判断。
IO流基础
els 方块边界变形处理
How to solve the error when mysql8 installs make
632. 最小区间
GIF making - very simple one-click animation tool
When Netflix's NFTs Forget Web2 Business Security
Deliver cloud-native microservices applications with Zadig
【无标题】
Multi-feature fusion face detection based on attention mechanism
IO stream basics
Simpson's paradox
els 方块变形
security 会话并发管理
22.支持向量机—高斯核函数