java--引用类型返回值解析
引用类型:
类:返回的是该类的对象。
案例:
案例:
案例:
引用类型:
类:返回的是该类的对象。
案例:
类Student:
package com.haust.day10.demo4;
public class Student {
public void study() {
System.out.println("好好学习!!");
}
}
类StudentDemo:
package com.haust.day10.demo4;
public class StudentDemo {
public Student getStudent(){
return new Student();
}
}
测试类:
package com.haust.day10.demo4;
public class Main {
public static void main(String[] args) {
//需求:在不直接创建对象的情况下使用StudentDemo中的getStudent方法
StudentDemo sd = new StudentDemo();
Student s = sd.getStudent();//调用方法,得到返回值Student的对象引用
s.study();//调用方法
}
}
抽象类:返回的是该抽象类的子类对象案例:
抽象类:Person:
package com.haust.day10.demo5;
public abstract class Person {
public abstract void study();
}
类:PersonDemo
package com.haust.day10.demo5;
public class PersonDemo {
public Person getPerson(){
//Person p = new Student();
//return p
//或者下面的方法
return new Student();
}
}
类Student:
package com.haust.day10.demo5;
public class Student extends Person {
public void study() {
System.out.println("好好学习!!");
}
}
测试类:
package com.haust.day10.demo5;
public class Main {
public static void main(String[] args) {
//需求:不直接创建对象的情况下使用Student类里面的study方法
PersonDemo pd = new PersonDemo();
Person p = pd.getPerson();//new Student --Person p = new Student();多态
p.study();
}
}
接口:返回的是该接口的实现类的对象。案例:
接口:Love
package com.haust.day10.demo6;
public interface Love {
public abstract void love();
}
类:LoveDemo
package com.haust.day10.demo6;
public class LoveDemo {
public Love getLove(){
Love l = new Student();
return l;
//or
//return new Student();
}
}
类Student:
package com.haust.day10.demo6;
public class Student implements Love {
public void love() {
System.out.println("学生爱学习!");
}
}
测试类:
package com.haust.day10.demo6;
public class Main {
public static void main(String[] args) {
//需求:使用Love中love方法输出学生爱学习!!
LoveDemo ld = new LoveDemo();
//实现多态
Love l = ld.getLove();
//调用方法传参:
l.love();
}
}