PROGRAM BASED ON CONSTRUCTORS
Constructor
Definition
1. In Java, a constructor is a block of codes similar to the method.
2. It is called when an instance of the class is created.
3. At the time of calling constructor, memory for the object is allocated in the memory.
4. It is a special type of method which is used to initialize the object.
5. Every time an object is created using the new keyword, at least one constructor is called.
6. It calls a default constructor if there is no constructor available in the class.
7. In such case, Java compiler provides a default constructor by default.
8. Types of Java Constructors
There are two types of constructors in Java:
1. Default Constructor (no-arg constructor)
Example:
public class ABC()
{
int x, y, z;
ABC() //default constructor
{
x=0;
y=0;
z=0;
}}
2. Parameterized Constructor
Example
public class ABC()
{
int x, y, z;
ABC(int p. int q, int r) //
{
x=p;
y=q;
z=r;
}}
P * R * O * G * R * A * M * S Y E A R W I S E
ICSE - Computer Application [2023]
Note : this Question was asked as Function Overloading
But Here Example shows Constructor Overloading
Question 1: Define a class to
overload the function print as follows:
void print() - to print the
following format
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
void print(int n) - To check whether
the number is a lead number. A lead number is the one whose sum of even digits
are equal to sum of odd digits.
e.g. 3669
odd digits sum = 3 + 9 = 12
even digits sum = 6 + 6 = 12
3669 is a lead number.
Solution:-
import java.util.Scanner;
public class print
{
public
void print()
{
for(int i = 1; i <= 5; i++)
{
for(int j = 1; j <= 4; j++)
{
System.out.print(i + " ");
}
System.out.println();
}
}
public
void print(int n)
{
int d = 0;
int evenSum = 0;
int oddSum = 0;
while( n != 0)
{
d = n % 10;
if (d % 2 == 0)
evenSum += d;
else
oddSum += d;
n = n / 10;
}
if(evenSum == oddSum)
System.out.println("Lead number");
else
System.out.println("Not a lead number");
}
public
static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Pattern: ");
System.out.print("Enter a number: ");
int num = in.nextInt();
print obj = new print(num);
}
}
No comments:
Post a Comment