Answers for "constructor overloading java"

1

constructor overloading

Constructor overloading in Java is a technique of having more than
one constructor with different parameter lists. 
They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number
of parameters in the list and their types.

class Student5{  
    int id;  
    String name;  
    int age;
    
    Student5(int i,String n){  
    	id = i;  					//creating two arg constructor
    	name = n;  
    }
    
    Student5(int i,String n,int a){  
    	id = i;  
    	name = n;					//creating three arg constructor    
    	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();  
   }  
}
Posted by: Guest on May-14-2021
0

constructor overloading in java

class Student{
	private String stuname;
	private String stuid;
	private int stuage;

	Student(){
		System.out.println("this a default constructor");
		
	}
	Student(String stuname,String stuid,int stuage){
		this.stuname=stuname;
		this.stuid=stuid;
		this.stuage=stuage;
	}

	public String getStudentName(){
		return stuname;
	}
	public String getStudentId(){
		return stuid;
	}
	public int getStudentAge(){
		return stuage;
	}

}

public class Constructor_OverloadingExample{
	public static void main(String[] args){
		Student stu=new Student();//calling the default constructor
		Student student=new Student("Khubaib","CSC-17F-129",22);//calling a parameterized constructor with sets the value of parameters
		System.out.println("Student Name: "+student.getStudentName());
		System.out.println("Student ID: "+student.getStudentId());
		System.out.println("Student Age: "+student.getStudentAge());


	}
}
Posted by: Guest on August-25-2021
0

Can we overload the constructors

Yes, the constructors can be overloaded by changing the number of 
arguments accepted by the constructor or by changing the data type of 
the parameters
Posted by: Guest on November-28-2020

Code answers related to "constructor overloading java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language