Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan's Comprehensive Exam #8

 
John Hembree
hired gun
Ranch Hand
Posts: 250
MS IE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question 10

Prints: main,B.m1
Why isn't this a compiler error at B.m1("main");? Is it because they are in the same file and that tells class C where B is? Although m1(String s) is a static method, I didn't think that B was created until new was used on it. Is the compiler doing something for me since the code is asking for B.m1("main");?
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John,
Welcome to the JavaRanch!
Static methods can be invoked directly on the class: there is no need for an instance of the class. Please note the statement
B.m1("main");
does not make use of a reference to an instance of the class B. Instead, the method is invoke on the class--not on an instance of the class.
 
John Hembree
hired gun
Ranch Hand
Posts: 250
MS IE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, for the response, it started to make more sense to me after I posted it. I started to think about the other static methods that are in your exams like Math.round(0.5f);, I don't have an instance of Math either but I can use the methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic