Anda di halaman 1dari 1

Concept of Instance and Class Variables 1 Class XI

public class try10 extends javax.swing.JFrame {

/** Creates new form try10 */


public try10() {
initComponents();
}
int a,b,c; // instance variables

static int x,y,z; // class variables or global variables

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


try10 t=new try10(); // an instance of class try10 being created here, ‘t’

try10.x=10; // u can access class variables by qualifying it with the class name
try10.y=12;
try10.z=14;

System.out.println(" Value of x:[ try10.x] " +try10.x);


System.out.println("Value of y:[try10.y] " +try10.y);  An instance or object of
System.out.println("Value of z: [try10.z]" +try10.z); a class can access both
instance and class/static
//try10.a=10; // error a class can't access an instance variable directly variables.
 An instance variable
can be accessed only
t.a=20; // fine as an object or instance of a class can access an instance variable by the instance of the
t.b=30; class.
t.c=40;  A class can’t access
instance variable
directly.
System.out.println(" Value of a:[ t.a] " +t.a);  Changes made to
System.out.println("Value of b:[t.b] " +t.b); instance variables by
System.out.println("Value of c: [t.c]" +t.c); an object is NOT
reflected in other
} objects of the same
class.
 Changes made to static
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { variables by an object
try10 t2=new try10(); // an instance or object of a class being created here ‘t2’ is reflected in other
object of the same
System.out.println(""); class.
System.out.println("");
System.out.println("");

System.out.println(" Value of x:[ try10.x] " +try10.x);


System.out.println("Value of y:[try10.y] " +try10.y);
System.out.println("Value of z: [try10.z]" +try10.z);

System.out.println(" Value of a:[ t2.a] " +t2.a); Output:


System.out.println("Value of b:[t2.b] " +t2.b); On Clicking Check1 Button:
System.out.println("Value of c: [t2.c]" +t2.c); Value of x:[ try10.x] 10
} Value of y:[try10.y] 12
Value of z: [try10.z]14
Value of a:[ t.a] 20
public static void main(String args[]) { Value of b:[t.b] 30
java.awt.EventQueue.invokeLater(new Runnable() { Value of c: [t.c]40
public void run() {
new try10().setVisible(true); On Clicking Check 2 Button
} Value of x:[ try10.x] 10
Value of y:[try10.y] 12
}); Value of z: [try10.z]14
} Value of a:[ t2.a] 0
Value of b:[t2.b] 0
// Variables declaration - do not modify Value of c: [t2.c]0
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
// End of variables declaration

Anda mungkin juga menyukai