示例程序:
import java.io.*; class Marks { //These variables are instance variables. //These variables are in a class and are not inside any function int engMarks; int mathsMarks; int phyMarks; } class MarksDemo { public static void main(String args[]) { //first object Marks obj1 = new Marks(); obj1.engMarks = 50; obj1.mathsMarks = 80; obj1.phyMarks = 90; //second object Marks obj2 = new Marks(); obj2.engMarks = 80; obj2.mathsMarks = 60; obj2.phyMarks = 85; //displaying marks for first object System.out.println("Marks for first object:"); System.out.println(obj1.engMarks); System.out.println(obj1.mathsMarks); System.out.println(obj1.phyMarks); //displaying marks for second object System.out.println("Marks for second object:"); System.out.println(obj2.engMarks); System.out.println(obj2.mathsMarks); System.out.println(obj2.phyMarks); } }
输出:
Marks for first object: 50 80 90 Marks for second object: 80 60 85
正如你在上面的程序中看到的那样,变量engMarks,mathsMarks,phyMarks是实例变量。如果我们有上述程序中的多个对象,则每个对象都有自己的实例变量副本。从上面的输出可以清楚地看到,每个对象都有自己的实例变量副本。