类作为方法参数与返回值
- 类作为方法参数
在编写程序中,会经常碰到调用的方法要接收的是一个类类型的情况,那么这时,要向方法中传入该类的对象。如下代码演示:
class Person{
public void show(){
System.out.println("show方法执行了");
}
}
//测试类
public class Test {
public static void main(String[] args) {
//创建Person对象
Person p = new Person();
//调用method方法
method(p);
}
//定义一个方法method,用来接收一个Person对象,在方法中调用Person对象的show方法
public static void method(Person p){
p.show();
}
- 类作为方法返回值
写程序调用方法时,我们以后会经常碰到返回一个类类型的返回值,那么这时,该方法要返回一个该类的对象。如下代码演示:
class Person{
public void show(){
System.out.println("show方法执行了");
}
}
//测试类
public class Test {
public static void main(String[] args) {
//调用method方法,获取返回的Person对象
Person p = method();
//调用p对象中的show方法
p.show();
}
//定义一个方法method,用来获取一个Person对象,在方法中完成Person对象的创建
public static Person method(){
Person p = new Person();
return p;
}
}
- 抽象类作为方法参数
今后开发中,抽象类作为方法参数的情况也很多见。当遇到方法参数为抽象类类型时,要传入一个实现抽象类所有抽象方法的子类对象。如下代码演示:
//抽象类
abstract class Person{
public abstract void show();
}
class Student extends Person{
@Override
public void show() {
System.out.println("重写了show方法");
}
}
//测试类
public class Test {
public static void main(String[] args) {
//通过多态的方式,创建一个Person类型的变量,而这个对象实际是Student
Person p = new Student();
//调用method方法
method(p);
}
//定义一个方法method,用来接收一个Person类型对象,在方法中调用Person对象的show方法
public static void method(Person p){//抽象类作为参数
//通过p变量调用show方法,这时实际调用的是Student对象中的show方法
p.show();
}
}