In: Computer Science
Create separate class with these members
a, b, c, x, y, z
int a b c
float x y z
Demonstrate
1) A two arg float constructor, and a two arg int constructor to instantiate objects, initialize variables read from the keyboard, display the sum.
Note:- Please type and execute this above java program and also give the output for both problems. (Type a java program)
The following is the code for the above question. The question says about the concept of Constructor Overloading. It is nothing but having one or more constructors but with different arguments. Here each constructor performs a different task. Here constructor works based on the input arguments we pass to it. The below code helps you to understand more.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter the two float numbers");
float f1,f2,sum_f;
f1=in.nextFloat();
f2=in.nextFloat();
Check c1=new Check(f1,f2);
sum_f=c1.x+c1.y;
System.out.printf("The sum of given float values is %.2f\n",sum_f);
System.out.println("Enter the two int numbers");
int i1,i2,sum_i;
i1=in.nextInt();
i2=in.nextInt();
Check c2=new Check(i1,i2);
sum_i=c2.a+c2.b;
System.out.printf("The sum of given int values is %d",sum_i);
}
}
class Check //declared a class named Check
{
int a,b,c; //delare int varibales
float x,y,z; //declare float variables
Check(int a,int b) //constructor which accepts two int arguments
{
this.a=a;
this.b=b;
}
Check(float x,float y) //constructor which accepts two float arguments
{
this.x=x;
this.y=y;
}
}
I am also attaching the output for your reference.
Output:
Enter the two float numbers
3.5
4.6
The sum of given float values is 8.10
Enter the two int numbers
8
14
The sum of given int values is 22
#Please dont forget to upvote if you find the solution helpful. Thank you.