返回值类型
一、分类
1.基本数据类型
2.引用数据类型
类:当类作为方法的返回值的时候,实际上需要返回一个该类的对象。
抽象类:当抽象类作为方法的返回值的时候,实际上需要返回一个该抽象类的一个具体子类的对象。
接口:
二、具体代码展示
1、类
class School1{
public void show(){
System.out.println("这是学校");
}
}
class SchoolDemo1{
public School1 show2() {
System.out.println("这是SchoolDemo1中的show2方法");
return new School1();
}
}
public class FanHuiZhi {
public static void main(String[] args) {
SchoolDemo1 sd1 = new SchoolDemo1();
School1 s1 = sd1.show2();//返回值是什么类型,就用什么类型接收
s1.show();
}
}
2、抽象类
```java
abstract class School3{
public void show(){
System.out.println("这是学校");
}
}
class SchoolDemo3 extends School3{
}
class SchoolDay{
public School3 show2(){
System.out.println("这是SchoolDay类的show2方法");
return new SchoolDemo3();//返回该抽象类的具体子类
}
}
public class FanHuiZhi1 {
public static void main(String[] args) {
SchoolDay sd = new SchoolDay();
School3 s1 = sd.show2();//父类引用指向子类对象,多态无法访问子类特有方法,需要向下转型
s1.show();
}
}
3、接口
```java
interface Demo3{
public abstract void show();
}
class Demo4 implements Demo3{
@Override
public void show() {
System.out.println("实现了接口Demo3中的show()方法");
}
}
class School4{
public Demo3 show2(){
System.out.println("这是School类中show2()");
return new Demo4();
}
}
public class FanHuiZhi2 {
public static void main(String[] args) {
School4 s4 = new School4();
// Demo3 d3 = s4.show2();//接口多态
// d3.show();
s4.show2().show();//链式编程
}
}