Reference Array
First we will have to create the any class, Here Student Class
class Student
{
private int y;
private String x;
Student(String s,int r)
{
x=s;
y=r;
}
public void SetRollNo(int x)
{
y = x;
}
public void SetName(String v)
{
x = v;
}
public String GetName(){
return x;
}
public int GetRollNo(){
return y;
}
}
In the following case array is directly initialized
class RefArrayDemo
{
public static void main(String args[])
{
//reference array std[] is created which contains the address of attributes of Student class.....
//by using new keyword object is created............
Student std[]={new Student("VIKESH",1240),
new Student("VED PRAKASH",1243),
new Student("ABBHISHEK",1260)
};//here in this case reference array is directly initialized
for(int i=0;i<std.length;i++)
{
String s = std[i].GetName();//by using that reference array we can access the GetName() method
int r =std[i].GetRollNo();//by using that reference array we can access the GetRollNo() method
System.out.println(s +"\t"+r);
}
}
}
In the following case array is initialized by user
import java.util.*;
class RefArrayDemo1
{
public static void main(String args[])
{
Student std[]= new Student[5];
Scanner scan = new Scanner(System.in);
//enter the different value of x and y
for(int i=0;i<std.length;i++)
{
System.out.println("ENTER THE VALUE OF X:");
String s =scan.next();
System.out.println("ENTER THE VALUE OF Y:");
int n = scan.nextInt();
std[i] = new Student(s,n); //the reference array std[] holds the different addresses of objects
}
for(int i=0;i<std.length;i++)
{
String s = std[i].GetName(); //calling of method defined in the given class
int n = std[i].GetRollNo();
System.out.println("X: "+s+"\t"+"Y:"+n);
}
}
}
No comments:
Post a Comment