Sie sind auf Seite 1von 3

For any java program there will be two classes

First class- instantiation

It contains the attributes, getters,setters and constructor

Second class- implementation

It contains the logic and main method

1. Given a student class with attributes id, name and branch.

Instatntiation Class:

Public class Student


{

//declaring attributes
private int id;
private String name;
private String branch;

//getters and setters


public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public int getName() {


return id;
}

public void setName(String name) {


this.name = name;
}

public int getBranch() {


return branch;
}

public void setBranch(String branch) {


this.branch = branch;
}

//constructor
public Student(int id, String name, String branch)
{
this.id = id;
this.name = name;
this.branch = branch;
}

So, first class is done. As you are doing in eclipse…. Just declare the attributes. In the toolbar
source”Generate getters and setters” (select all) and again “Generate Constructor using fields”

Second class (implementation)

Create a class Solution with main method

In main method We will create number of objects specified.

If he asks to create 3 student class objects

Student[] s=new Student[3];

S[0]=new Student(1,”teju”,”ECE”);

S[1]=new Student(2,”moh”,”CSE”);

S[2]=new Student(3,”test”,”CSE”);

So, now we have created 3 student objects

There are three possibilities for logic method

Declare the method with with proper return type and specified attributes.

Let the method name be findById(Student[] stud, int id): Student

Here the method is with array of student attribute and the return type is Student

So we need to pass findById(s) from main method

Public Class Solution

Public Static void main( String args[])

Student[] s=new Student[3];

S[0]=new Student(1,”teju”,”ECE”);

S[1]=new Student(2,”moh”,”CSE”);

S[2]=new Student(3,”test”,”CSE”);
Student stu= findById(s,3);

System.out.println(stu.getId());

System.out.println(stu.getName());

System.out.println(stu.getBranch());

Public Student findById( Student[] stud, int id)

For(i=0;i<stud.length;i++)

If(stud[i].getId()==id)

Student st= new Student(stud[i].getId(), stud[i].getName(),stud[i].getBranch());

return st;

Stud.length gives the number of objects in array of stud i.e 3

While accessing array of objects

Stud[i].getId() This notation is atmost important

.Don’t write stud.getId because stud is array of objects ; not a single object

As return type is student we need to return that particular object which matches the id

When it matches create a student object for the purpose of returning

And store that particular details into that object

Das könnte Ihnen auch gefallen