Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble calling methods from a class/

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Multiple markers at this line

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

>Solution :

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());  
 }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading