今天又重新听了 Java 基础+进阶的视频,尝试不看视频自己写下Java中将类作为方法传参和返回的代码,发现还是有很多问题。
第一个,将类的对象作为方法的参数传入,直接上代码
package com.liepin.rim.org.day06;
public class Four {
public static void main(String[] args){
Three three = new Three();
String str = three.name;
int num = three.num;
// System.out.println(num);
// System.out.println(str);
//这个Three类的对象three中保存的内容为: str和num
method(three);
// Three four = getThree(); //左边进行接收,赋值调用
// System.out.println(four.name);
// System.out.println(four.num);
}
public static void method(Three three){ //类的方法作为参数
System.out.println(three.name);
System.out.println(three.num);
}
// public static Three getThree(){
// Three three = new Three();
// three.num = 100;
// three.name = "world!";
// return three; //谁调用了我,我就把类的对象three的地址传给谁
// }
}
package com.liepin.rim.org.day06;
public class Three {
int num = 1;
String name = "Hello";
}
首先,创建一个类 Three, 在类中定义两个成员变量:
int num = 1;
String name = “Hellol”;
然后新建一个类,在新建类的main方法中对第一个类进行实例化
Three three = new Three();
然后打印该类的对象 three.num和three.name
接着新建一个方法 method() 将 three作为参数传入, 参数类型是类Three
public static void method(Three three)
第二个,将类作为方法的返回,谁调用了我,我就把类的对象three的地址传给谁,具体看代码
package com.liepin.rim.org.day06;
public class Four {
public static void main(String[] args){
// Three three = new Three();
// String str = three.name;
// int num = three.num;
// System.out.println(num);
// System.out.println(str);
//这个Three类的对象three中保存的内容为: str和num
//method(three);
Three four = getThree(); //左边进行接收,赋值调用
System.out.println(four.name);
System.out.println(four.num);
}
public static void method(Three three){ //类的方法作为参数
System.out.println(three.name);
System.out.println(three.num);
}
public static Three getThree(){
Three three = new Three();
three.num = 100;
three.name = "world!";
return three; //谁调用了我,我就把类的对象three的地址传给谁
}
}
新建一个有返回的方法,对第一个类进行实例化
Three three = new Three();
然后对第一个类中原有的成员变量进行重新赋值,最后返回 第一个类的对象
在main方法中再实例化一次,将有返回的方法赋值给新实例化的对象
Three four = getThree();
然后打印这个对象调用的变量。这时候打印出来的就是新的对象调用的成员变量
这块之前一直没有完全弄明白。这次算是明白了,但是还是需要多做题来巩固下。
所以为啥测试中掌握 Python 语言的同学居多,也可以理解了。因为面向对象这块还有Java的一些基本规则,理解起来确实有难度。
大家加油~