Skip to content
Advertisement

Trouble calling methods from a class/ [closed]

Can someone tell me whats wrong with these codes ?

public class Student {
    String name;
    int roll_no;
    public void getDetails(String Name, int roll) {
        name = Name;
        roll_no = roll;
    }
}

and this

public class StudentRun {
    Student student = new Student();
    String n = "John";
    int r = 2;
    student.getDetails(n, r);
}

It shows the error:

Multiple markers at this line

on the line where i call the student.getDetails(n,r)

Advertisement

Answer

You cannot call a method in a class without it being wrapped in a method.

Your Student class also lacks a constructor (a method that is called when the class is instantiated) and lacks the context of attribute visibility (public/protected/private). The constructor must call itself as the class, in your case:

public class Student {
 protected String name;
 protected int roll_no;
 public Student(String Name, int roll) {
    this.name = Name;
    this.roll_no = roll;
 }

 public String getName() {
  return this.name
 } 
 ....
}

Once you have structured the class correctly, you need to do the following to instantiate it:

class OtherClass {
 public static void main (String[] args) {
 student = new Student("John", 42);
 System.out.println(student.getName());  
 }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement