Java中将自定义的类作为参数传递到普通的方法中和自定义的类作为普通的方法的返回值类型

1. 将自定义的类作为参数传递到普通的方法中

main函数里面直接调用Student里面的类,然后可以使用对象调用对应的属性和方法。

但是也可以在main函数对应的.java文件中定义普通方法,那么这些普通方法是怎么调用Student类呢?

package mode5类;

public class Student {
	String name;
	int age;

	public void eat() {
		System.out.println("吃饭");
	}

	public void sleep() {
		System.out.println("睡觉");
	}
}
--------------------------------------------------------------------------
package mode5类;

public class Mode3 {
	public static void main(String[] args) {
		Student stu = new Student();
		stu.name = "张三";
		stu.age = 18;
		getStudent(stu);
	}
	public static void getStudent(Student stu) {
		System.out.println(stu.name);
	}
}

定义普通类时要将实例化对象作为参数,那么要传入参数是哪个类,然后传入这个类的对象。

2. 自定义的类作为普通的方法的返回值类型

package mode5类;

public class Student {
	String name;
	int age;

	public void eat() {
		System.out.println("吃饭");
	}

	public void sleep() {
		System.out.println("睡觉");
	}
}
--------------------------------------------------------------------------
package mode5类;

public class Mode3 {
	public static void main(String[] args) {
		System.out.println(getStudent().name);
	}
	public static Student getStudent() {
		Student stu = new Student();
		stu.name = "李四";
		stu.age = 15;
		return stu;
	}
	public static void getStudent(Student stu) {
		System.out.println(stu.name);
	}
}

这样就可以将自定义的类作为返回值返回了。

你可能感兴趣的:(学习Java)