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.
Related
This question already has answers here:
Java: How to access methods from another class
(6 answers)
Closed 6 years ago.
How to use the getvolume() method defined by the Box class in the boxweight class? I know that I have to instantiate the Box class in order to use the method defined by it, but how?
class Box {
private int lenght;
private int breadth;
private int height;
int price;
Box(int l, int b, int h) {
lenght= l;
breadth= b;
height= h;
}
public Box(int p) {
price= p;
}
double getvolume() {
return lenght*height*breadth;
}
void setsize(int $l, int $b, int $h ) {
lenght= $l;
breadth= $b;
height= $h;
}
}
public class boxclassdemo {
public static void main(String[] args) {
Box mybox1=new Box(10,10,10);
Box mybox2=new Box(5,5,5);
Box mybox3=new Box(20);
System.out.println(mybox1.getvolume());
System.out.println(mybox2.getvolume());
System.out.println(mybox3.price);
}
}
The boxweight class:
public class boxweight {
int weight;
int length,breadth,height;
public static void main(String[] args) {
boxweight myboxx = new boxweight();
myboxx.weight= 25;
myboxx.length=10;
myboxx.breadth=20;
myboxx.height=30;
}
}
You can find the answer to your question, as well to many other questions you doubtlessly will have soon on Oracle Java Tutorial on Object Creation
As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.
The same goes for actually using these, the very next tutorial:
Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:
objectReference.fieldName
I recommend for you to either start reading these tutorials or get yourself a good java book, there's plenty out there.
It looks as though you want to use inheritance. If you define BoxWeight like this, note the 'extends Box' after the class name:
public class BoxWeight extends Box {
int weight;
BoxWeight(int l, int b, int h, int w) {
super(l, b, h);
weight = w;
}
}
Then you can treat a boxweight object as if it were a Box object, which means you can use it's public methods, like so:
public static void main(String[] args) {
BoxWeight myboxx = new BoxWeight(10, 20, 30, 25);
double volume = myboxx.getvolume();
}
(By the way, the first letter of class name usually be upcast.
If you use Eclipse or other IDE, it will help you create when you do the follow step.
Box box = new Box(25, 10, 20, 30);
Then,
System.out.println(box.getvolume());
For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.
I am trying to write a porting of glm in java.
At the moment I created a package jglm and inside this package there are all the different classes Mat4, Vec4, Vec3, etc..
Such as:
public class Mat {
protected float[] matrix;
protected int order;
}
I can call them by typing
jgml.Mat4 modelviewMatrix = new Jgml.Mat4(1.0f);
And this is fine..
Now I am writing also some methods, like
mix(x, y, lerp)
And I also would like to use this as stated, that is
float value = jglm.mix(x, y, lerp)
But of course in this case Jglm must be a class...
Is there a way to conjugate the two things together?
Edit: If I create a class jglm.Jglm
package jglm;
/**
*
* #author gbarbieri
*/
public class Jglm {
public class Mat {
protected float[] matrix;
protected int order;
}
public class Mat4 extends Mat {
public Vec4 c0;
public Vec4 c1;
public Vec4 c2;
public Vec4 c3;
public Mat4(float value) {
order = 4;
matrix = new float[16];
for (int i = 0; i < 4; i++) {
matrix[i * 5] = value;
}
c0 = new Vec4(matrix, 0);
c1 = new Vec4(matrix, 4);
c2 = new Vec4(matrix, 8);
c3 = new Vec4(matrix, 12);
}
public float[] toFloatArray() {
return new float[]{
c0.x, c0.y, c0.z, c0.w,
c1.x, c1.y, c1.z, c1.w,
c2.x, c2.y, c2.z, c2.w,
c3.x, c3.y, c3.z, c3.w,};
}
}
public static float mix(float start, float end, float lerp) {
return (start + lerp * (end - start));
}
}
When I try to instantiate
cameraToClipMatrix_mat4 = new Jglm.Mat4(1.0f);
I get "an enclosing instance that contains Jglm.Mat4 is required"
At the moment I created a package Jglm and inside this package there are all the different classes Mat4, Vec4, Vec3, etc..
In Java, packages must be named in all lowercase. Naming it the way you did will surprise anyone who looks at your code and may also cause serious name-resolution issues for the compiler.
It is also customary to import all classes we are using so we refer to them just by their simple name in code. Perhaps you could consider declaring
package org.example.jglm;
public class Jglm {
public static void mix(double x, double y, Lerp lerp) {
...
}
}
on the client side, you'd write
import org.example.Jglm;
void someMethod() {
Jglm.mix(x,y,lerp);
}
In general, when you need some pure functions in your code, then declare them as static methods. Look at java.lang.Math source code for guidance.
Declare all your methods in Mat class as static
which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class.
Ex: ClassName.methodName(args)
See Class Methods in http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Having all the methods in your Jglm class as static will enable the method calls, both by instance and by classname.
I am new to Java. So the question may seem naive... But could you please help?
Say for example, I have a class as follows:
public class Human {
private float height;
private float weight;
private float hairLength;
private HairState hairTooLong = new HairState() {
#Override
public void cut(Human paramHuman) {
Human.this.decreaseHairLength();
}
#Override
public void notCut(Human paramHuman) {
Human.this.increaseHairLength();
}
};
public float increaseHairLength () {
hairLength += 10;
}
public float decreaseHairLength () {
hairLength -= 10;
}
private static abstract interface HairState {
public abstract void cut(Human paramHuman);
public abstract void notCut(Human paramHuman);
}
}
Then I have another class as follow:
public class Demo {
public static void main(String[] args) {
Human human1 = new Huamn();
Human.HairState.cut(human1);
}
}
The statement
Human.HairState.cut(human1);
is invalid...
I intend to call the public cut() function, which belongs to hairTooLong private attribute.
How should I do it?
Since HairState is private to Human, nothing outside the Human class can even know about it.
You can create a method in Human that relays the call to its private mechanism:
public class Human {
. . .
public float cutHair() {
return hairTooLong.cut(this);
}
}
and then call that from main():
System.out.println(human1.cutHair());
Two other solutions to previous comment:
You can implement a getter which returns the hairTooLong attribute.
You can invoke the the cut() method through the reflection API (but you don't want to go there if you are beginner).
Would suggest either the solution in the previous comment, or the first option presented here.
If you are curious, you can have a look to the reflection API and an example here: How do I invoke a Java method when given the method name as a string?
In java there are four access levels, default, private, public and protected. Visibility of private is only limited to a certain one class only (even subclass cannot access). You cannot call private members in any other class. Here is a basic details of java access levels.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
For more details check Oracle docs
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.