您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
javase第二季学习笔记-匿名对象
发布时间:2017-07-10 14:22:44编辑:雪饮阅读()
匿名对象就是定义一个没有名称的对象
该对象的特点是只能使用一次
该对象之间在堆中开辟内存空间
该对象使用后成为垃圾对象,被gc回收。
匿名对象概念仅仅是在类的实例化上的语法。
public class NewKeywordDemo
{
public static void main(String[] args){
//因为没有声明直接实例化,声明是一个变量名存储于栈内存中,而直接实例化则是在堆内存中
new Person().xy("雪饮");
}
}
//非public的类其类名称可以和文件名不一致
class Person
{
public void xy(String name){
System.out.println("我的名字是:"+name);
}
public void xy(String name,char sex){
System.out.println("我的名字是:"+name+"性别是:"+sex);
}
}
一般来说,如果有显式声明其他构造方法,那么默认构造方法也是要显式声明的,因为后面javaee等的好多框架中都要调用这个默认的无参的构造方法。
面向对象示例:
设计一个学生类,根据计算机分数、体育分数、音乐分数。输出学生的总分,平均分,最高分,最低分。
public class NewKeywordDemo
{
public static void main(String[] args){
//因为没有声明直接实例化,声明是一个变量名存储于栈内存中,而直接实例化则是在堆内存中
Study xy = new Study("雪饮",100.00f,98.00f,100.00f);
xy.showStudy();
}
}
//非public的类其类名称可以和文件名不一致
class Study
{
private String name;
private float js;
private float ty;
private float yy;
//默认构造方法,一般保留
public Study(){}
//构造方法
public Study(String name,float js,float ty,float yy){
this.name=name;
this.js=js;
this.ty=ty;
this.yy=yy;
}
//求总分
public float total(){return this.js+this.ty+this.yy;}
//求平均分
public float svg(){return this.total()/3;}
//求最高分
public float max(){
float max=this.js>this.ty?this.js:this.ty;
max=max>this.yy?max:this.yy;
return max;
}
//求最低分
public float min(){
float min=this.js<this.ty?this.js:this.ty;
min=min<this.yy?min:this.yy;
return min;
}
//输出学生全部信息
public void showStudy(){
System.out.println("学生名字是:"+this.name+"总分是:"+this.total()+"平均分是:"+this.svg()+"最高分是:"+this.max()+"最低分是:"+this.min());
}
}
关键字词:javase,匿名对象