What is the reason behind “non-static method cannot be referenced from a static context”? [duplicate]

This question already has answers here: Non-static variable cannot be referenced from a static context (15 answers) Closed 7 years ago. The community reviewed whether to reopen this question 3 months ago and left it closed: Original close reason(s) were not resolved The very common beginner mistake is when you try to use a class … Read more

What is the difference between a static and a non-static initialization code block

My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to any function. For example following code compiles: public class Test { private static final int a; static { a = 5; doSomething(a); } private static … Read more

What is the difference between static func and class func in Swift?

I can see these definitions in the Swift library: extension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) -> Bool } protocol BooleanLiteralConvertible { typealias BooleanLiteralType class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self } What’s the difference between a member function defined as static func and another one defined as class func? Is it simply that … Read more

Mocking static methods with Mockito

I’ve written a factory to produce java.sql.Connection objects: public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory { @Override public Connection getConnection() { try { return DriverManager.getConnection(…); } catch (SQLException e) { throw new RuntimeException(e); } } } I’d like to validate the parameters passed to DriverManager.getConnection, but I don’t know how to mock a static method. I’m using … Read more

What does the ‘static’ keyword do in a class?

To be specific, I was trying this code: package hello; public class Hello { Clock clock = new Clock(); public static void main(String args[]) { clock.sayTime(); } } But it gave the error Cannot access non-static field in static method main So I changed the declaration of clock to this: static Clock clock = new … Read more

Static vs class functions/variables in Swift classes?

The following code compiles in Swift 1.2: class myClass { static func myMethod1() { } class func myMethod2() { } static var myVar1 = “” } func doSomething() { myClass.myMethod1() myClass.myMethod2() myClass.myVar1 = “abc” } What is the difference between a static function and a class function? Which one should I use, and when? If … Read more