I'm almost completely new to Java and programming in general (my main degree is in Law but I'm hoping to open myself up to programming as I truly believe it's going to be an essential skill in a couple years).
I've created two classes, LabClass
and Student
, and the point is to enroll students into the class, while giving them credits for enrolling.
Here's the method in my Student
class that I'm trying to access:
public void addCredits(int additionalPoints)
{
credits += additionalPoints;
}
And here's the method in my LabClass
class that I'm trying to use:
public void enrollStudent(Student newStudent)
{
if(students.size() == capacity) {
System.out.println("The class is full, you cannot enrol.");
}
else {
students.add(newStudent);
}
students.addCredits(50);
}
What I don't understand is why BlueJ says that it cannot find the method "addCredits". I'm a real beginner so I'm sorry if this is a stupid question, but any help would be much appreciated!
In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.
Class B inherits from Class A, and I want class A to be able to call a function created in class B. using namespace std; class B; class A { public: void CallFunction () { B b; b. bFunction(); } }; class B: public A { public: virtual void bFunction() { //stuff done here } };
You never show what the variable students
is. However it seems to be an array of Student
s. You're invoking addCredits
on an array of Students
, instead of on the variable newStudent
, which is what I suppose you want to do. The correct way of doing this would be:
public void enrollStudent(Student newStudent)
{
if(students.size() == capacity) {
System.out.println("The class is full, you cannot enrol.");
}
else {
newStudent.addCredits(50);
students.add(newStudent);
}
}
Students is an ArrayList or something... not a student. I think maybe you mean to say newStudent.addCredits(50);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With