PREVIOUS
*/
Constructors:
/*constructor:
* class name and constructor name must be same.
* constructor is invoked when the obj is created.
* constructor have no return type not even
void.
Types of constructors
There are two types of constructors:
- default constructor (no-arg constructor)
- parameterized constructor
*/
CONSTRUCTOR:
import java.io.*;
class con2
{
con2()
{
System.out.println("This is a default
constructor");
}
con2(int a,int b)
{
System.out.println("A value:"+a+"\nB
value:"+b);
}
con2(String na,float m)
{
System.out.println("String
value:"+na+"\nFloat value:"+m);
}
public static void main(String ar[])throws
IOException
{
int x,y;
float s;
String sa;
DataInputStream ss=new DataInputStream(System.in);
x=Integer.parseInt(ss.readLine());
y=Integer.parseInt(ss.readLine());
s=Float.parseFloat(ss.readLine());
sa=ss.readLine();
con2 c0=new con2();
con2
c1=new con2(x,y);
con2 c2=new con2(sa,s);
}
}
//Constructor Using This Key Word
this keyword is used to reference of the
instance variable
import java.io.*;
class con3
{
float t;
int a,b;
con3(int p,int q)
{
this.a=p;
this.b=q;
System.out.println("the val of a,b "+a+"\t "+b+ "\tadd :"+(a+b));
}
int rectarea()
{
return a*b;
}
con3(float f)
{
t
this.t=f;
}
float cir(float t)
{
return
(3.14f*t*t);
}
public static void main(String ar[])throws
IOException
{
int k,l;
float s;
DataInputStream d=new DataInputStream(System.in);
k=Integer.parseInt(d.readLine());
l=Integer.parseInt(d.readLine());
s=Float.parseFloat(d.readLine());
con3 c=new con3(k,l);
con3 c1=new con3(s);
System.out.println("the val of rectarea"
+c.rectarea());
System.out.println("the val of
circle"+c1.cir(s));
}
}
/* Constructor Overloading */
same function name with diff arg
class conovr
{
conovr() //default
constructor
{
System.out.println("This is default
constructor");
}
conovr(int x,int y)
{
System.out.println("The int is:" +x+
"\t" +y);f
}
conovr(String m,float n)
{
System.out.println("The string &
float:"+m+ "\t" +n);
}
public static void main(String ar[])
{
conovr co=new conovr();
conovr c1=new conovr(100,200);
conovr c2=new conovr(" thuya",123.123f);
}
}
No comments:
Post a Comment