1.类成员变量、成员方法的简单调用
创建Student类,包含属性 (成员变量):姓名、年龄、性别。包含行为(成员方法)准备学习、学习中、学习结束。
class Student{
String name;
int age;
String gender;
// 创建行为(成员方法)
// 无具体返回值类型study()方法
public void study(){
System.out.println("到点了,我准备学习了!");
}
// 返回一个字符串类型的studing()方法,一个字符串类型的参数
public String studing(String className){
return "学习"+className+"中。。。。。";
}
// 返回一个字符串类型的studyEnd()方法,一个整数类型的参数
public String studyEnd(int time){
return "我学了"+time+"个小时了,该休息了!";
}
}
// StudentTest测试类
public class StudentTest{
public static void main(String[] args){
// new一个Student类型的对象
Student stu=new Student();
// 对对象进行赋值,数据要与成员变量数据类型一致
stu.name="小明";
stu.age=18;
stu.gender="女孩";
// 打印已赋值的成员变量
System.out.println("我的名字叫"+stu.name+",我今年"+stu.age+"岁了,"+"可以看出我是一个"+stu.gender+"。");
// 调用成员方法
stu.study();
System.out.println(stu.studing("Java"));
System.out.println(stu.studyEnd(6));
}
}
我的名字叫小明,我今年18岁了,可以看出我是一个女孩。
到点了,我准备学习了!
学习Java中。。。。。
我学了6个小时了,该休息了!
2.匿名对象的简单使用
首先创建一个新的StudentTest测试类,暂时创建Student类型对象及StudentDemo类型对象来进行调用,将Student类型对象作为实际参数进行传递。
class Student{
public void show(){
System.out.println("匿名对象的简单使用!");
}
}
class StudentDemo{
public void method(Student stu){
stu.show();
}
}
public class StudentTest{
public static void main(String[] args){
Student stu=new Student();
StudentDemo stuDemo=new StudentDemo();
stuDemo.method(stu);
}
}
匿名对象的简单使用!
可以看见,如果对象只调用方法一次,我们new对象会很繁琐,这里我们引用匿名对象来完成。
class Student{
public void show(){
System.out.println("匿名对象的简单使用!");
}
}
class StudentDemo{
public void method(Student stu){
stu.show();
}
}
public class StudentTest{
public static void main(String[] args){
// Student stu=new Student();
// StudentDemo stuDemo=new StudentDemo();
// stuDemo.method(stu);
// 创建匿名对象来进行成员方法引用及参数传递
new StudentDemo().method(new Student());
}
}
匿名对象的简单使用!