user3115941 user3115941 - 1 year ago 78
Java Question

Cannot Find Method of an Object in ArrayList

So I get the error "cannot find symbol - method getIsNational()" in class Ex6,
here is the code for all the classes involved

public class Message
private String sender;
private String receiver;
private String content;

public Message(String ssender, String rreceiver, String ccontent){

public String getSender(){
return sender;

public String getReceiver(){
return receiver;

public String getContent(){
return content;

Above is the super class Message with some getter methods

public class NationalMessage extends Message
private boolean isNational;
public NationalMessage(String ssender, String rreceiver, String ccontent){
super(ssender, rreceiver, ccontent);
if(ssender.startsWith("UK") && rreceiver.startsWith("UK")){ //If the sender and reciever are from uk then it is national
isNational = true;
}else{//if not then it isnt national
public boolean getIsNational(){
return isNational;

Above is the subclass NationalMessage

import java.util.*;
public class Ex6 {
public static int countNational (ArrayList<Message> messageList) {
// This method just adds up the amount of Messages that are of type NationalMessage and when getIsNational is true.
int sum = 0;
for(int i = 0; i < messageList.size(); i++){ //loop through arraylist given
if(messageList.get(i) instanceof NationalMessage){//if its of this type continue
if((messageList.get(i)).getIsNational()){ //Error occurs here
sum += 1;
return sum;
}catch(NullPointerExcpetion e){//in the case of messageList being null
return -1;
public static void main(String[] args){ // you can use this main method to test your
ArrayList<Message> messageList = new ArrayList<Message>();
messageList.add(new NationalMessage("UKJohn","UKMark","aa"));
messageList.add(new NationalMessage("UKJohn","FRJean","aa"));
messageList.add(new Message("Mike","John","aa"));

And the class above is where I get the error on line 9, I dont understand why it cannot find the method, im sure it is a simple fix, but how do I resolve this?
Thanks in advance for your help.

Answer Source

When you are invoking getIsNational() in the messageList element, the compiler thinks that the object is of type Message. But there is no method in Message with that name, so you should cast the element to NationalMessage like below

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download