新运算符通过为新对象分配内存并返回对该内存的引用来实例化类。新的操作符也调用类的构造函数。
// Class Declaration
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}
public static void main(String[] args)
{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
输出:
Hi my name is tuffy. My breed,age and color are papillon,5,white
Dog tuffy = new Dog("tuffy","papillon",5, "white");
注意:所有类都至少有一个构造函数。如果一个类没有显式声明任何东西,Java编译器会自动提供一个无参的构造函数,也称为默认构造函数。这个默认构造函数调用父类的无参数构造函数(因为它只包含一个语句,即super();),或者如果该类没有其他父类,则为Object类构造函数(因为Object类是所有类的父类,直接或间接)。
创建类的对象的方法
在java中有四种创建对象的方法,严格来说只有一种方法(使用new关键字),其余的内部使用new关键字。
// creating object of class Test Test t = new Test();
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
// creating object of class Test Test t1 = new Test(); // creating clone of above object Test t2 = (Test)t1.clone();
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();