public static void main(String[] args) {
printIdea(new Idea());
}
public static void printIdea(Idea idea) {
System.out.println(Idea.getDescription()); // this won't work - "Cannot make a static reference to the non-static method
} // System.out.println(idea.getDescription()); is working fine
public static class Idea {
public String getDescription() {
return "Amigo";
}
}
}
What's the difference between calling the getDescription() method of the Idea class with lower case and upper case? Can't figure this out, could someone help me please or provide a relavant article/link?
This below is also working fine, but does not match the task condition (I changed the getDescription() method to static and called the getDescription() method with the upper case Idea):
public static void main(String[] args) {
printIdea(new Idea());
}
public static void printIdea(Idea idea) {
System.out.println(Idea.getDescription());
}
public static class Idea {
public static String getDescription() {
return "Amigo";
}
}
}
Hey guys, what's the difference between Idea.getDescription() and idea.getDescription()?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Misiu
6 August 2020, 21:12solution
Kiedy uruchamiamy program do pamięci komputera wczytywany jest kod klasy. Kod klasy może zawierać dane statyczne i niestatyczne.
Dostęp od danych niestatycznych możliwy jest jedynie poprzez instancję, obiekt klasy.
W pierwszym przypadku metoda getDescription() jest niestatyczna. Dostęp do niej możliwy jest dopiero po utworzeniu obiektu tej klasy. Wywołanie metody polega na podaniu referencji do obiektu, kropki i nazwy metody. W tym przypadku utworzony obiekt ma referencję "idea", więc wywołanie wygląda tak:
idea.getDescription()
W drugim przypadku metoda getDescription() jest statyczna. Do jej wywołania wystarczy kod klasy, który to kod jest już w pamięci komputera. Nie trzeba tworzyć obiektu klasy.
Wywołanie jest następujące: nazwaKlasy, kropka, nazwa metody. Czyli:
Idea.getDescription()
Błąd wskazany przez Ciebie:
Poprzez nazwę klasy (czyli w sposób statyczny) próbujesz wywołać metodę niestatyczną, czyli metodę dostępną jedynie poprzez obiekt klasy.
+4
Jakub Gotowski
8 August 2020, 11:33
super, wszystko jasne, dzięki wielkie! :)
0