Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #13074

Re: Beginners Problem - Static reference to non-static method

Date 2012-03-20 06:13 -0700
From Patricia Shanahan <pats@acm.org>
Newsgroups comp.lang.java.programmer
Subject Re: Beginners Problem - Static reference to non-static method
References <jk9vfl$gfl$1@theodyn.ncf.ca>
Message-ID <R9WdnfwTEIAOH_XSnZ2dnUVZ_oqdnZ2d@earthlink.com> (permalink)

Show all headers | View raw


William Colls wrote:
> I am novice with Eclipse, and a beginner with Java, but I have 20+ years 
> experience as a programmer - coming to OO late in life.
> 
> I Have some code that looks like this:
> 
> // begin java
> 
> package com.mine.package
> 
> class MyClass {
> 
>   import java.io.*
> 
>   public static void main() {
> 
>     try {
>         runMyMethod();             // <---- error here
>     }
>     catch (Exception e) {
>        System.out.println(e.getMessage());
>     }
>   }
> 
>   public void runMyMethod() throws Exception {
>       // do some things
>   }
> }
> 
> // end java
> 
> However, Eclipse generates the error "Cannot make static reference to to 
> non-static method in type MyClass" at the point noted.
> 
> I understand what it means (I think), but I don't understand why it is a 
> problem, and more importantly - How to fix it. There is a whole bunch 
> more stuff in the class. Making runMyMethod static fixes the problem 
> here, but then everything else in the class also has to be static.


You have two options at this point:

1. Make all those methods static.

2. Create an object, and reference its methods:

new MyClass().runMyMethod();

Patricia

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Beginners Problem - Static reference to non-static method William Colls <william.colls@rogers.com> - 2012-03-20 09:07 -0400
  Re: Beginners Problem - Static reference to non-static method Patricia Shanahan <pats@acm.org> - 2012-03-20 06:13 -0700
  Re: Beginners Problem - Static reference to non-static method Lew <noone@lewscanon.com> - 2012-03-20 06:34 -0700
  Re: Beginners Problem - Static reference to non-static method William Colls <william.colls@rogers.com> - 2012-03-20 10:21 -0400
  Re: Beginners Problem - Static reference to non-static method Gordon Levi <gordon@address.invalid> - 2012-03-21 02:15 +1100
  Re: Beginners Problem - Static reference to non-static method Roedy Green <see_website@mindprod.com.invalid> - 2012-03-20 11:28 -0700

csiph-web