Answers for "overloaded constructor java"

1

Overload the default constructor to take a parameter for each attribute and set it

class StudentData
{
   private int stuID;
   private String stuName;
   private int stuAge;
   StudentData()
   {
       //Default constructor
       stuID = 100;
       stuName = "New Student";
       stuAge = 18;
   }
   StudentData(int num1, String str, int num2)
   {
       //Parameterized constructor
       stuID = num1;
       stuName = str;
       stuAge = num2;
   }
   //Getter and setter methods
   public int getStuID() {
       return stuID;
   }
   public void setStuID(int stuID) {
       this.stuID = stuID;
   }
   public String getStuName() {
       return stuName;
   }
   public void setStuName(String stuName) {
       this.stuName = stuName;
   }
   public int getStuAge() {
       return stuAge;
   }
   public void setStuAge(int stuAge) {
       this.stuAge = stuAge;
   }

   public static void main(String args[])
   {
       //This object creation would call the default constructor
       StudentData myobj = new StudentData();
       System.out.println("Student Name is: "+myobj.getStuName());
       System.out.println("Student Age is: "+myobj.getStuAge());
       System.out.println("Student ID is: "+myobj.getStuID());

       /*This object creation would call the parameterized
        * constructor StudentData(int, String, int)*/
       StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
       System.out.println("Student Name is: "+myobj2.getStuName());
       System.out.println("Student Age is: "+myobj2.getStuAge());
       System.out.println("Student ID is: "+myobj2.getStuID()); 
  }
}
Posted by: Guest on October-04-2020
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

Code answers related to "overloaded constructor java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language