Class XII subhashv1224@gmail.
com Page 1 of 3
Class XII q. adding values of two objects into third object
** Coding behind a java class namely Student
public class Student {
int a; // an instance variable
int b; // an instance variable
public void printvar(){ // an instance method
System.out.println(“a : “+ a+" b: "+b);
}
public Student(){ // a non-parameterized constructor
a=10;
b=20;
}
public Student(int x,int y){ // a parameterized constructor
a=x;
b=y;
}
Two parameters of type Student
public void add2obj(Student s1,Student s2){ // an instance method
a=s1.a+s2.a;
b=s1.b+s2.b;
}
} // end class
*** Coding behind a jFrame’s button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Student st1=new Student(); // calling non-parameterized constructor
Student st2=new Student(100,200); // calling parameterized constructor
Student st3=new Student();
st3.add2obj(st1, st2);
st1.printvar();
st2.printvar();
st3.printvar();
}
Class XII [email protected] Page 2 of 3
Class XII Q. A class that will swap two numbers as well as increment the value of its data
members by 1.
*** create a java class namely SwapByRef as following:
public class SwapByRef {
int x,y;
void printvar(){
System.out.println("x= "+ x + " y= "+y);
}
public SwapByRef(int f,int s){ // parameterized constructor
x=f;
y=s;
}
public void swap(){ // function swap
int t;
t=x;
x=y;
y=t;
}
public void incr(){ // function incr to increment x and y by 1
x++;
y++;
}
} // end class
*** create a jFrame form and code the following behind two buttons:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // this button calls ‘swap’ method
SwapByRef s=new SwapByRef(10,20); // creating object s
System.out.print("Before swap :" );
s.printvar();
s.swap(); // calling swap method … an instance method
System.out.print("After swap :" );
s.printvar();
} // end button1 method
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // this button calls ‘incr’ method
SwapByRef s=new SwapByRef(10,20); // creating object s
System.out.print("Before Incrementing :" );
s.printvar();
s.incr(); // calling incr() method… an instance method
System.out.print("After incrementing :" );
s.printvar();
} // end button2 method
Class XII
[email protected] Page 3 of 3