什么是构造方法?
只要有一个对象实例化则就会调用构造方法。
在构造方法中要注意以下几点:
—构造方法的名称必须与类名一致
—构造方法的声明处不能有任何返回值类型的声明
—不能在构造方法中使用return返回一个值。
class Person{
public Person(){ // 声明构造方法
System.out.println("一个新的Person对象产生。") ;
}
};
public class ConsDemo01{
public static void main(String args[]){
System.out.println("声明对象:Person per = null ;") ;
Person per = null ; // 声明对象时并不去调用构造方法
System.out.println("实例化对象:per = new Person() ;") ;
per = new Person() ;//实例化对象
}
};
有时候在编写类的时候并没有定义构造方法,也可以执行,实际上这是属于JAVA操作机制,在整个Java的操作中,如果一个类中没有明确声明一个构造方法,则会自动生成一个无参的什么都不做不执行任何操作的狗仔方法供用户使用。类似于以下形式。
注意:如果为类提供了一个构造方法,则不会再生成一个无参无操作的构造方法。如果再直接new Person()就会出现异常,所以再提供其他构造方法的时候也要额外添加一个无参数无操作的构造方法。
匿名对象:匿名就是没有名字,在Java中如果一个对象只使用一次,则就可以将其定义为匿名对象。所谓的匿名对象就是比普通对象少了一个栈的引用而已。如下所示:
class Person{
private String name ;
private int age ;
public Person(String n,int a){ // 声明构造方法,为类中的属性初始化
this.setName(n) ;
this.setAge(a) ;
}
public void setName(String n){
name = n ;
}
public void setAge(int a){
if(a>0&&a<150){
age = a ;
}
}
public String getName(){
return name ;
}
public int getAge(){
return age ;
}
public void tell(){
System.out.println("姓名:" + this.getName() + ";年龄:" + this.getAge()) ;
}
};
public class NonameDemo01{
public static void main(String args[]){
new Person("张三",30).tell() ;
}
};
类的设计分析:
class Student{
private String stuno ;
private String name ;
private float math ;
private float english ;
private float computer ;
public Student(){}
public Student(String s,String n,float m,float e,float c){
this.setStuno(s) ;
this.setName(n) ;
this.setMath(m) ;
this.setEnglish(e) ;
this.setComputer(c) ;
}
public void setStuno(String s){
stuno = s ;
}
public void setName(String n){
name = n ;
}
public void setMath(float m){
math = m ;
}
public void setEnglish(float e){
english = e ;
}
public void setComputer(float c){
computer = c ;
}
public String getStuno(){
return stuno ;
}
public String getName(){
return name ;
}
public float getMath(){
return math ;
}
public float getEnglish(){
return english ;
}
public float getComputer(){
return computer ;
}
public float sum(){ // 求和操作
return math + english + computer ;
}
public float avg(){ // 求平均值
return this.sum() / 3 ;
}
public float max(){ // 求最高成绩
float max = math ; // 数学是最高成绩
max = max>computer?max:computer ;
max = max>english?max:english ;
return max ;
}
public float min(){ // 求最低成绩
float min = math ; // 数学是最高成绩
min = min<computer?min:computer ;
min = min<english?min:english ;
return min ;
}
};
public class ExampleDemo01{
public static void main(String args[]){
Student stu = null ; // 声明对象
stu = new Student("MLDN-33","李兴华",95.0f,89.0f,96.0f) ;
System.out.println("学生编号:" + stu.getStuno()) ;
System.out.println("学生姓名:" + stu.getName()) ;
System.out.println("数学成绩:" + stu.getMath()) ;
System.out.println("英语成绩:" + stu.getEnglish()) ;
System.out.println("最高分:" + stu.max()) ;
System.out.println("最低分:" + stu.min()) ;
}
};