java 参数 返回值_Java基础(方法参数和方法的返回值)

本文探讨了Java中方法参数的使用,包括类、抽象类和接口作为参数的情况,并通过示例代码进行说明。同时,文章也阐述了方法返回值的概念,同样展示了普通类、抽象类以及接口作为返回值的示例。
摘要由CSDN通过智能技术生成

1.方法参数

类作为方法参数:传递的是该类的对象

抽象类作为方法参数 :传递的是该抽象类的子类对象

接口作为方法参数: 传递的是该接口的实现类对象

代码示例:

package day0526;

public class demo3 {

public static void main(String[] args) {

Student student=new Student();

m1(student);

Zi zi=new Zi();

m2(zi);

Ziinter ziinter=new Ziinter();

m3(ziinter);

}

//普通类

public static void m1(Student student){

System.out.println(student.name);

}

//抽象类

public static void m2(Abstractclass a){

System.out.println(a.name);

}

//接口

public static void m3(Inters inters){

System.out.println(inters.name);

}

}

class Student{

String name="yyy";

}

abstract class Abstractclass{

String name="wtc";

}

class Zi extends Abstractclass {

}

interface Inters{

String name="yw";

}

class Ziinter implements Inters{

}

2.返回值

普通类作为方法返回值:返回该类的对象

抽象类作为方法返回值:返回该抽象类的子类对象

接口作为方法返回值:返回该接口的实现类对象

代码示例:

package day0526;

public class demo4 {

public static void main(String[] args) {

Students a=m1();

System.out.println(a.name);

}

//普通类

public static Students m1(){

Students s=new Students();

return s;

}

//抽象类

public static AbPerson m2(){

AbPerson a=new PersonAb();

return a;

}

//接口

public static Interfuction m3(){

Interfuction i=new ZiImpl();

return i;

}

}

class Students{

String name="yyy";

}

abstract class AbPerson{

String name="wtc";

}

class PersonAb extends AbPerson{

}

interface Interfuction{

String name="wy";

}

class ZiImpl implements Interfuction{

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值