今天学习了java中的三个关键字,总结如下:
关键字return的用法:
有返回值类型:数据类型(基本数据类型,引用数据类型)
return 数据;//结束方法体,并返回一条数据
无返回值类型:void
return;//结束方法体
注意区别 System.out.println();和return;的区别:
前者,仅仅是打印操作 ;后者,是返回值操作
以下为测试实例:
package _0302;
public class ReturnType {
public void test1(int a,int b){
System.out.println(a+b);
}
public int test2(int a,int b){
return a+b;
}
public static void main(String[] args) {
ReturnType rt = new ReturnType();
rt.test1(11, 12);
System.out.println(100+rt.test2(13, 14));
}
}
运行结果为:
23
127
关键字this的用法:
1.当成员变量被局部变量隐藏时,我们要访问被隐藏的成员变量,需要使用this来访问
含义:this表示当前对象(当前执行的方法所属的对象)
例如:this.ele=ele;
2.当一个构造器中的部分代码和另一个构造器的方法体完全相同时,我们为了减少代码的重复定义,使用this来调用另一个结构体的方法体
使用:this(参数)
含义:当前类的构造器
例如:this();
以下为测试实例:
this用法一:
package _0302;
public class TestThis {
public int a;
public int b;
public void ll(int a,int b){
this.a=a;
this.b=b;
System.out.println(a+" "+b);
System.out.println(this.a+this.b);
}
public static void main(String[] args) {
TestThis t1 = new TestThis();
TestThis t2 = new TestThis();
t1.ll(12, 13);
System.out.println(t1.a+" "+t1.b );
t2.ll(15, 13);
System.out.println(t2.a+" "+t2.b );
}
}
this用法二:
package _0302;
public class TestThis2 {
int a,b,c;
public TestThis2() {
System.out.println("创建一个对象");
}
public TestThis2(int a) {
this();
this.a=a;
}
public TestThis2(int a,int b) {
this(a);
this.b=b;
}
public TestThis2(int a,int b,int c) {
this(a,b);
this.c=c;
}
private void test() {
TestThis2 t1 = new TestThis2();
TestThis2 t2 = new TestThis2(12);
TestThis2 t3 = new TestThis2(12,23);
TestThis2 t4 = new TestThis2(12,23,34);
}
public static void main(String[] args) {
TestThis2 t = new TestThis2();
t.test();
}
}
运行结果为;
创建一个对象
创建一个对象
创建一个对象
创建一个对象
创建一个对象
static关键字:
类成员:
使用static修饰的成员变量和成员方法称为类成员
使用static修饰的成员变量称为类变量
使用static修饰的成员方法称为类方法
实例成员:
未使用static修饰的成员变量和成员方法称为类成员
未使用static修饰的成员变量称为类变量
未使用static修饰的成员方法称为类方法
类成员是属于类的,同时被所有对象共享
实例成员是该类的对象所独有的
类方法中不能使用this
以下为测试所用的代码:
public class StaticTest {
int a;
static int b;
public void dodo(int a){
b = a;
System.out.println("传入参数为"+a);
System.out.println(this.a);
System.out.println("类变量b为"+b);
}
public static void doso(int a) {
b = a;
StaticTest t = new StaticTest();
t.a = b;
System.out.println(t.a);
System.out.println("传入参数为"+a);
System.out.println("类变量b为"+b);
}
public static void main(String[] args) {
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
st1.a=11;
st1.b=12;
st1.dodo(11);
st1.doso(12);
System.out.println("对象st1的成员变量a为"+st1.a);
System.out.println("对象st1的成员变量b为"+st1.b);
st2.a=15;
st2.b=16;
System.out.println("对象st2的成员变量a为"+st2.a);
System.out.println("对象st2的成员变量a为"+st2.b);
st2.dodo(11);
st2.doso(12);
}
}
包是java用于访问保护和命名空间管理的方式
包的声明;package 包名;
java语法规范:
一个源文件内可以定义多个类;
一个源文件内最多有一个公共的类;公共的类必须与源文件名相同;非公共的类可以和源文件不同;
一个源文件可以有多个类,编译时会生成多个字节码文件,一个字节码文件对应一个类 并与该类的名字相同
修饰符:
private 本类内部 不能被继承
(default) 本类内部+同包其他类 能被同包继承
protected 本类内部+同包其他类+其他包子类 能被继承
public 公开,能被所有类访问 能被继承