Java, how to create a class similar to Math - java

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.

Related

How does a class use a method defined in another class in Java? [duplicate]

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());

'Must qualify the allocation with an enclosing instance of type Types'

Firstly, I know this question has already been answered, however, I've looked through all the answers I could find and none of them helped.
I'm making a game in LibGDX, to simulate physics with large pixels. To create the different kinds of pixels, I've decided to make classes inside my Types class, empty space will also be a kind of pixel which I'll render as black, so I have a class within Types called None, which will be used for emptiness.
In my Main class, I create an ArrayList which contains ArrayLists which contains instances of Types:
public ArrayList<ArrayList<Types>> grid;
...
for (int y = 0; y < 151; y++) {
ArrayList<Types> row = new ArrayList<Types>();
for (int x = 0; x < 105; x++) {
row.add(Types.None);
}
grid.add(row);
}
And, my Types class looks like this:
package io.j4cobgarby.github;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
public class Types {
public static Types None = new None();
public float mass;
public Color colour;
public boolean dynamic;
public boolean conducts_electrons;
public float conducts_heat;
public Types(float mass, Color colour, boolean dynamic, boolean conducts_electrons, float conducts_heat) {
this.mass = mass;
this.colour = colour;
this.dynamic = dynamic;
this.conducts_electrons = conducts_electrons;
this.conducts_heat = conducts_heat;
}
public void getInput() {
}
public void dynamUpdate() {
}
public void staticUpdate() {
}
public void delete() {
}
public class None extends Types {
public None() {
super(0.0f, Color.BLACK, false, false, 0.0f);
}
#Override
public void getInput () {
if (Gdx.input.isKeyJustPressed(Keys.T)) {
System.out.println("T pressed");
}
}
}
}
So what I hopes was that I would now have an ArrayList containing 151 other ArrayLists, each containing 105 instances of Types.None
But, this doesn't work.
On line 10 of Types - public static Types None = new None(); - I get this error:
No enclosing instance of type Types is accessible. Must qualify the allocation with an enclosing instance of type Types (e.g. x.new A() where x is an instance of Types).
Why is this? I've tried many things, but I can't seem to get it working.
Thanks.
Since you are assigning an instance of the None class to a static field, the None class must also be decleared static. Non-static inner classes can only exist within an instance of their outer class.
public static class None extends Types {
...
}

Making a static duplicate of non-static integer

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.

Java extending classes mess

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.

How to call a public method WITHIN a private attribute?

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

Categories

Resources