一、匿名对象
匿名对象就是没有明确给出名字的对象,一般匿名对象只使用一次,而且匿名对象只在堆内存中开辟空间,而不存在栈内存的引用
class Person{
private String name;
private int age;
public Person(String name,int age){ //定义构造方法为属性初始化
this.setName(name); //为 name 属性赋值
this.setAge(age); //为 age 属性赋值
}
public void tell(){
System.out.println("name: " + name + "\t"+ "age: " + age);
}
public String getName(){ // 取得姓名
return name;
}
public void setName(String name) { //设置姓名
this.name = name; // this.方法名称 表示强调是本类中的方法
}
public int getAge() { //取得年龄
return age;
}
public void setAge(int age) { //设置年龄
this.age = age;
}
}
public class Test{
public static void main(String[] args) {
new Person("java",30).tell(); //匿名对象
}
}
此处直接使用了new Person("java",30)
语句,这实际上就是一个匿名对象,与之前声明的对象不同,此处由于没有任何栈内存引用此块堆内存空间,所以该对象使用一次之后就等待被垃圾收集机制回收
匿名对象实际上就是一个堆内存空间,对象不管是匿名还是非匿名,都必须在开辟堆内存空间之后才可以使用
二、实例讲解
package Chapter_5;
class Student{ //定义学生类
private String stuno; //学号
private String name; //姓名
private float math; //数学成绩
private float english; //英语成绩
public Student(){} //定义无参构造
public Student(String stuno,String name,float math,float english){ //定义有五个参数的构造
this.setStuno(stuno);
this.setName(name);
this.setMath(math);
this.setEnglish(english);
}
public void setStuno(String s){
this.stuno = s;
}
public void setName(String n){
this.name = n;
}
public void setMath(float m){
math = m;
}
public void setEnglish(float e){
english = e;
}
public String getStuno(){
return stuno;
}
public String getName(){
return name;
}
public float getMath(){
return math;
}
public float getEnglish(){
return english;
}
public float sum(){
return this.math + this.english;
}
};
public class Example {
public static void main(String[] args) {
Student stu = new Student("MLDN-33","Java",95.f,89.0f);
System.out.println("学生编号:" + stu.getStuno());
System.out.println("学生姓名:" + stu.getName());
System.out.println("总成绩:" + stu.sum());
}
}
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51