链式编程
/*
链式编程。
每次调用完毕方法后,返回的是一个对象。
*/
class Student {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class StudentDemo {
public Student getStudent() {
return new Student();
}
}
class StudentTest3 {
public static void main(String[] args) {
//如何调用的呢?
StudentDemo sd = new StudentDemo();
//Student s = sd.getStudent();
//s.study();
//大家注意了
sd.getStudent().study();
}
}
例子
package com.toltech.bean;
/**
* Created by wanggs on 2017/9/22.
*/
public class LinkProgram {
private String mText;
private int mId;
private boolean isAdd;
public static void main(String[] args) {
LinkProgram link = new LinkProgram();
//链式接口调用时,返回值类型和link该对象类型保持一致
link.setAdd(true)
.setId(5)
.setText("hello world");
System.out.println(link);
}
//返回值类型为LinkProgram
public LinkProgram setText(String mText) {
this.mText = mText;
return this;
}
//返回值类型为LinkProgram
public LinkProgram setId(int mId) {
this.mId = mId;
return this;
}
//返回值类型为LinkProgram
public LinkProgram setAdd(boolean isAdd) {
this.isAdd = isAdd;
return this;
}
@Override
public String toString() {
return "LinkProgram{" +
"mText='" + mText + '\'' +
", mId=" + mId +
", isAdd=" + isAdd +
'}';
}
}
接口作为形参
/*
引用类型
类名:(匿名对象的时候其实我们已经讲过了)需要的是该类的对象
抽象类:需要的是该抽象的类子类对象
接口:需要的是该接口的实现类对象
*/
//定义一个爱好的接口
interface Love {
public abstract void love();
}
class LoveDemo {
public void method(Love l) { //l; l = new Teacher(); Love l = new Teacher(); 多态
l.love();
}
}
//定义具体类实现接口
class Teacher implements Love {
public void love() {
System.out.println("老师爱学生,爱Java,爱林青霞");
}
}
class TeacherTest {
public static void main(String[] args) {
//需求:我要测试LoveDemo类中的love()方法
LoveDemo ld = new LoveDemo();
Love l = new Teacher();
ld.method(l);
}
}