PJ 5
PJ 5
i
thi
Ex-program : DemoCon3.java
import java.util.Scanner;
ipa
class Display3
{ Ma
//x and y are Instance variables memory in Object
int x,y;
sh
Display3(int x,int y)
ate
{
nk
this.x=x;
Ve
this.y=y;
void dis()
System.out.println("****Method-dis()*****");
System.out.println("The value x:"+x);
class DemoCon3
i
{
thi
public static void main(String[] args)
ipa
Scanner s = new Scanner(System.in);
Ma
System.out.println("Enter the value-1:");
int v1 = s.nextInt();
d.dis();//method_call
nk
}
Ve
o/p:
12
13
****Method-dis()*****
---------------------------------------------------------------
i
ClassFiles:
thi
Display3.class
DemoCon3.class(MainClass)
ipa
Ma
sh
ate
nk
Ve
==================================================================
Advantage of Constructors:
application.
===================================================================
===
faq:
i
thi
define "this" keyword?
=>"this" keyword will hold the reference of object from where constructor or
ipa
method executing.
===================================================================
sh
=
ate
*imp
1.Using Constructor
Ve
1.Using Constructor:
Ex:
DemoCon3.java
i
=>we use Object reference variables(Object names) to load the data to
thi
Objects.
Ex:
ipa
DemoCon1.java
Ex : DemoCon4.java
ate
import java.util.Scanner;
class Customer
nk
{
Ve
int no;
String name;
this.no=no;
}
this.name=name;
i
int getNo()
thi
{
return no;
ipa
}
String getName()
{
Ma
return name;
sh
}
ate
class DemoCon4
nk
int no = Integer.parseInt(s.nextLine());
i
c.setNo(no);
thi
c.setName(name);
ipa
//Calling Geeter methods
int n = c.getNo();
Ma
String nm = c.getName();
sh
System.out.println("CustNo:"+n);
ate
System.out.println("Name:"+nm);
}
nk
o/p:
Ve
1234
Raj
CustNo:1234
Name:Raj
===================================================================
==
faq:
=>The methods which are used to set the data to objects are known as "Setter"
i
thi
methods.
ipa
faq:
methods.
sh
ate
=>Every variable in class must have its own Setter and Getter method.
nk
===================================================================
=========
Ve
Assignment:
SubClass : UserDetails
Variables : name,mId,phNo
Constructor : UserDetails(name,mId,phNo)
MainClass : DemoUser
===================================================================
==========
i
thi
ipa
Ma
sh
ate
nk
Ve