I cannot compile the following code:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
The following error appears:
Non-static method calcArea(int, int) cannot be referenced from static content
What does it mean? How can I resolve that issue..?
EDIT:
Based from your advice, I made an instance which is new test() as follows:
public class Test {
int num;
public static void main (String [] args ){
Test a = new Test();
a.num = a.calcArea(7, 12);
System.out.println(a.num);
}
int calcArea(int height, int width) {
return height * width;
}
}
Is this correct? What is the difference if I do this...
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
Your main is a static, so you can call it without an instance of class test (new test()). But it calls calcArea which is NOT a static: it needs an instance of the class
You could rewrite it like this I guess:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
As comments suggests, and other answers also show, you might not want to go this route for evertyhing: you will get only static functions. Figure out what the static actually should be in your code, and maybe make yourself an object and call the function from there :D
What Nanne suggested is definitely a fix for your problem. However, I think it would be prudent if you got in to the habit right now, while you are early in your progression of learning java, of trying to use static methods as little as possible, except where applicable (utility methods, for instance). Here is your code modified to create an instance of Test and call the calcArea method on your Test object:
public class Test {
public static void main (String [] args ){
Test test = new Test();
int a = test.calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
As you get further in to coding with java and, presumably given the code you've just written start dealing with objects such as polygon objects of some sort, a method like calcArea belongs at the instance context and not the static context so it can operate on the internal state of your objects. This will make your code more Object Oriented and less procedural.
calcArea mustn't be static. For using another methods in main class, you must create an instance of its.
public class Test {
public static void main (String [] args ){
Test obj = new Test();
int a = obj.calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
Do you know what a static method is?
If not, look it up, but the short answer is that a static method does not (can not) access "this" because it is not assigned to any particular instance of the class. Therefore you can't call an instance method (one that isn't static) from within a static one, because how will the computer know which instance should the method be run on?
If a method is defined as static that means you can call that method over the class name such as:
int a = Test.calcArea(7, 12);
without creating an object,
here; Test is the name of the class, but to do this calcArea() method must be static or you can call a non-static method over an object; you create an object by instantiating a class such as:
Test a = new Test();
here "a" is an object of type Test and
a.calcArea(7,12);
can be called if the method is not defined as static.
your class calcArea should be declared static and if you want to use that class, you have to first create an instance of the class. In the class the parameters of the class should be returned, as someone suggested.
Related
I've just started learning about constructors and know that they're used to initialize objects. But i noticed that objects can be given initial values in the declaration (as in example 2) without having to specify them separately in a constructor.
Both examples below give the same result so what is the benefit of first declaring the attribute and then specifying the value in a constructor instead of right away in the declaration?
Example 1:
**public class Main {
int x;
public Main() {
x = 5;
}**
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Example 2:
**public class Main {
int x = 5;**
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
In your example, where you always want to set the value to a pre-defined value, a constructor is not required. It can be initialized at the time the attribute is defined. However, in most cases, it is not so simple - value of a class attribute is usually passed in at the time an instance is created. In such cases, a constructor is a good way to initialize the attributes of a class.
public class Main {
int x;
public Main(int x) {
this.x = x;
}
public static void main(String[] args) {
Main myObj = new Main(6);
System.out.println(myObj.x);
}
}
I want to create a wrapper class that calls static methods and member fields from a class that is provided by a library I am unable to view the code.
This is to avoid boilerplate setting code of the global member fields when I need to use a static method in a specific context.
I want to try to avoid creating wrapper methods for each static method.
My question:
Is it possible to return a class with static methods from a method to access just the static methods without instantiating it?
Code is below with comments in-line.
The code is used to demonstrate a change in a static value when the method getMath() is invoked.
I want to avoid the setting of the value before calling the static method.
StaticMath.setFirstNumber(1);
StaticMath.calc(1);
StaticMath.setFirstNumber(2);
StaticMath.calc(1);
I am using the Eclipse IDE and it comes up with Warnings, which I understand, but want to avoid.
I tried searching for something on this subject, so if anyone can provide a link I can close this.
public class Demo {
// Static Methods in a class library I don't have access to.
static class StaticMath {
private static int firstNum;
private StaticMath() {
}
public static int calc(int secondNum) {
return firstNum + secondNum;
}
public static void setFirstNumber(int firstNum) {
StaticMath.firstNum = firstNum;
}
}
// Concrete Class
static class MathBook {
private int firstNum;
public MathBook(int firstNum) {
this.firstNum = firstNum;
}
// Non-static method that gets the class with the static methods.
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
// I don't want to instantiate the class.
return new StaticMath();
}
}
public static void main(String... args) {
MathBook m1 = new MathBook(1);
MathBook m2 = new MathBook(2);
// I want to avoid the "static-access" warning.
// Answer is 2
System.out.println(String.valueOf(m1.getMath().calc(1)));
// Answer is 3
System.out.println(String.valueOf(m2.getMath().calc(1)));
}
}
I'd just wrap it to make for an atomic operation:
public static class MyMath{
public static synchronized int myCalc( int num1 , int num2 ){
StaticMath.setFirstNum(num1);
return StaticMath.calc(num2);
}
}
Drawback: You'll have to make sure, StaticMath is not used avoiding this "bridging" class.
Usage:
int result1 = MyMath.myCalc( 1, 1 );
int result1 = MyMath.myCalc( 2, 1 );
You shouldnt call a static method through an object reference. You should directly use class reference to call a static method like this:
StaticMath.calc(1)
But if you still need it for some reason, you can return null in getMath method, but you will still get warning in Eclipse:
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
return null;
}
I infer that question is not properly asked if the answer is not
StaticMath.calc(1)
Other issue you may be facing due to package visibility to static inner classes. Which is a design choice by the writer of Demo class. If you can mark your classes MathBook and StaticMath public then you can access them like below:
Demo.StaticMath.calc(1);
I don't know what pot I was smoking when I posted the original, but I came to my senses and came up with this. I am not an experienced coder, but the entire post was made mostly as a question that for the most part has been answered. I now know classes can't have code directly in them, and more so about the core structure.
class Shape {
public static void ShapeAttemptTwo()
{
class Circle extends Shape
{
public static CircleAttemptTwo()
{
int pi = 3.14;
int r=4;
}
}
class Rectangle extends Shape
{
public static Rectangle()
{
int l = 14;
int b = 10;
int z = l*b;
}
}
class Square extends Shape
{
public static Square()
{
int a = 11;
System.out.println(a * a);
}
}
// Java code 7, invalid method declare, return type required. (public static //CircleAttemptTwo())
// I'm lost on this one, could I have some help?
// and reached end of file while parsing }, confusing to me.
/EDIT THANK YOU VERY MUCH. The constructive crit. really helped, as I ended up with a lot of knowledge and my final code was
class Shape {
public static void ShapeAttemptTwo()
{
class Circle extends Shape
{
public static CircleAttemptTwo()
{
int pi = 3.14;
int r=4;
}
}
class Rectangle extends Shape
{
public static Rectangle()
{
int l = 14;
int b = 10;
int z = l*b;
}
}
class Square extends Shape
{
public static Square()
{
int a = 11;
System.out.println(a * a);
}
}
You're doing several things wrong:
1) Your "static main()" belongs inside a class
2) You can only have one "public class" per module.
SUGGESTED CHANGE:
public abstract class Shape
{
public static void main(String[] args) {
Shape rectangle = new Rectangle (14, 10);
System.println ("rectangle's area=" + rectangle.getArea ());
...
}
}
class Circle extends Shape {
...
}
class Rectangle extends Shape {
int l;
int b;
public Rectangle (int l, int b) {
this.l = l;
this.b = b;
}
public int getArea () {
return l * b;
}
}
...
Aside from the errors Tomas pointed out:
5) You forgot the word class in the Square declaration.
6) You cannot declare a public class directly inside a method. Java does allow you to declare classes, called "local classes" inside methods. However, I'm not sure if that's what you really want to do; if you do, you can only use Circle inside your main method, so you're not really creating a hierarchy. Anyway, when you declare a local class, it can't have public, protected, or private keywords on it, so that explains the first error message you're seeing.
EDIT: Based on the second post: Every method has to have a return type; if you don't actually want the method to return anything, the return type should be void. Thus:
public static void CircleAttemptTwo()
{
//int pi = 3.14; should be
double pi = 3.14;
int r=4;
}
However, constructors don't need a return type, but they can't be static. So public Square() and public Rectangle() are OK. CircleAttemptTwo doesn't match the class name, so it isn't a constructor.
"reached end of file" usually means you're missing a }, as you did here.
And 3.14 isn't an integer.
Are you joking? You're missing basic knowledges of Java:
1) Method yea doesn't have a return type.
2) There's a code directly inside the class Rectangle, not in method.
3) There's a code directly inside the class Square, not in method.
4) You're using very strange and weird code-style and formatting.
Update: Formatting has been fixed.
2nd Update:
1) Code has been changed and it's formatted wrong again.
2) There are three static methods without defined return type.
Here are some more informations related on the topic.
You need to change
int pi = 3.14;
to
double pi = 3.14;
Also, static method is in wrong place.
When I try to compile this code I get an error saying
"
Rectangle.java:35: error: non-static variable this cannot be referenced from a static context
this.inDemand = inDemand;
"
I found a workaround by renaming the inDemand argument to isInDemand and removing the this prefix from inDemand in the setInDemand method. I am just trying to understand why what I was doing initially didn't work.
The code is below:
public class Rectangle extends Polygon
{
private double height;
private static boolean inDemand = false;
private double width;
public Rectangle()
{
this(1,1,"None");
}
public Rectangle(double height, double width, String id)
{
super(id);
this.height = height;
this.width = width;
}
public double getArea()
{
return this.height*this.width;
}
public double getTotal()
{
if(inDemand == true)
{
return 2 * this.getArea();
}
else
{
return this.getArea();
}
}
public static void setInDemand(boolean inDemand)
{
this.inDemand = inDemand;
}
public static void main(String[] args)
{
Rectangle rect = new Rectangle();
rect.setInDemand(true);
System.out.println(rect.getTotal());
}
}
public static void setInDemand(boolean inDemand)
{
this.inDemand = inDemand;
}
this is not allowed in static methods as it refers to the current object. Assume a scenario when you call this method in a static way without creating an instance. Here is what i mean:
Rectangle.setInDemand(true);
is a legal call to this method but not on an instance rather using the class name.
inDemand is declared to be a static field. Any field or method with that declaration can only be referenced in a static context.
The simplest thing to do would be to remove static from that boolean and method signature, since its usage suggests it's a property of the object Rectangle.
You would declare a field or a method static if and only if it didn't need to be a property of the class itself, but held information about the class (i.e. Integer.MAX_VALUE), or could be used to produce a an instance of that object (i.e. Integer.valueOf(2)).
this referes to the currently executing object. static methods are not part of object, they are part of class. So you cannot reference currently executing object using static methods
Remove static modifier for the field
You can't do this.inDemand as this means doing an operation on the current object. As it is static, you do not have an object instantiated.
I've been doing some tutorial on inheritance abstract class, and I pass an array to a function for a calculation of total price. But then, when I tried to call the function in the main, it didn't work and I've got some error according the method call.
Here is my calculation code in subclasses :
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if (a[i]=="a")
price=24.90;
}
double tot=price+qty[i];
return tot;
}
This is my method call in the for loop. I don't know how to call the method as the error says "non-static method calcPrice() cannot be referenced from a static context"
for(int i=0;i<=num;i++) {
System.out.println("\t"+a[i]+"\t\t\t"+qty[i]+" "+calcPrice());
}
The main method is static, and can't call non-static code. You have 2 solutions.
Create an instance of the class performing the calculation, and call calcPrice on that instance.
make calcPrice static.
I suggest option one as you've been doing research on classes. This would be good practice for you.
Also do not compare variable a to "a" with ==. Use .equals instead. Check this link for why.
Edit:
I'm not sure how an abstract class plays into this as you have no abstract methods needing implementation.
public class CalcClass{
public double calcPrice(String[] a, int[] qty, int num){
int i =0;
for(i=0;i<=num;i++) {
if ("a".equals(a[i]))
price=24.90;
}
double tot=price+qty[i];
return tot;
}
}
public class MainClass{
public static void main(String[] args){
//create instance of calc class
CalcClass c = new CalcClass();
//call calc price method on calcclass
c.calcPrice(a, new int[]{1}, 1};
}
}
Changed to-
public static double calcPrice(String[] a, int[] qty, int num){
...
}
You should create an object before you do a call from main. Say you have a class-
public class Test {
public void someMethod(){
}
public static void main(String... args){
// Create an object first
Test t = new Test();
// Now you can use that non-static method someMethod
t.someMethod();
}
}
For static method, they exist on load.
You will need to create instance in order to call you method since your method is not static.
making you methos static will enable you to use it without creating instance of the class.
you may want to read about Static Methods here