默认构造函数(无参数构造函数)
参数化构造函数
<class_name>(){}
在此示例中,我们在Bike类中创建no-arg构造函数。将在创建对象时调用它。 |
//Java Program to create and call a default constructor
class Bike1{
//creating a default
constructorBike1(){
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default
constructorBike1 b=new Bike1();
}
}
Bike is created
//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//method to display the value of id and namevoid
display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the
objects1.display();
s2.display();
}
}
0 null
0 null
//Java Program to demonstrate the use of the parameterized constructor.class Student4{
int id;
String name;
//creating a parameterized constructor Student4(int i,String n){
id = i;
name = n;
}
//method to display the values void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects and passing values Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object s1.display();
s2.display();
}
}
111 Karan
222 Aryan
//Java program to overload constructorsclass Student5{
int id;
String name;
int age;
//creating two arg constructor Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
111 Karan 0
222 Aryan 25
Java构造函数 | Java方法 |
构造函数用于初始化对象的状态。 | 一种方法用于揭示对象的行为。 |
构造函数不得具有返回类型。 | 方法必须具有返回类型。 |
构造函数被隐式调用。 | 该方法被显式调用。 |
如果类中没有任何构造函数,则Java编译器会提供默认构造函数。 | 在任何情况下编译器都不提供该方法。 |
构造函数名称必须与类名称相同。 | 方法名称可以与类名称相同或不相同。 |
通过构造函数
通过将一个对象的值分配给另一个对象
通过Object类的clone()方法
//Java program to initialize the values from one object to another object.class Student6{
int id;
String name;
//constructor to initialize integer and string Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
111 Karan
111 Karan
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
111 Karan
111 Karan