This is using Processing 3.5, not every java thing works the same here.
The Bird class is giving me the error saying it needs to implement call(). Isn't it already under the main? I'm not experienced with interfaces so I don't know what exactly is going on here.
public interface FuncCall<A> {
A call();
}
class Bird implements FuncCall{
//Error here ^
//The type FuncCallTest.Bird must implement the inherited abstract method FuncCallTest.FuncCall.call()
//Is this not implemented already under main?
float x, y, size;
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Bird(float x, float y, float size){
this.x = x;
this.y = y;
this.size = size;
}
public void main(String[] args){
FuncCall<Float> getX = new FuncCall<Float>(){
#Override
public Float call(){
return x;
}
};
FuncCall<Float> getY = new FuncCall<Float>(){
#Override
public Float call(){
return y;
}
};
FuncCall<Float> getSize = new FuncCall<Float>(){
#Override
public Float call(){
return size;
}
};
inputs.add(getX);
inputs.add(getY);
inputs.add(getSize);
}
}
class Pol {
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Pol(ArrayList<FuncCall<Float>> inputs){
this.inputs = inputs;
}
//public float call(ArrayList<FuncCall<Float>> arr, int index){
//return arr.get(index).call();
//}
//How do I do this? Do I need to implement the interface here as well? Because if so same error as on Bird
}
I'll also stick this extra bit on the end here.
System.out.println(pol.call(pol.inputs, 1));
Does will that work? It doesn't error before compiling.
I appreciate any help. Please ask if something doesn't make sense as I'm still new to stack and not the best with java. :)
main file :
void setup(){
Bird bird = new Bird(1.2, 3.2, 7.5);
Pol pol = new Pol(bird.inputs);
System.out.println(pol.call(pol.inputs, 1););
}
First of all you could skip your FuncCall interface and use Java's Supplier functional interface and just add these Suppliers respectively method references of your class objects getters to the list.
Another approach is to provide an interface or abstract class that has getters and/or member variables for x, y and size and use this interface or abstract class as type parameter for the list.
With Suppliers:
This is closer to your example and requires less changes in
your code.
The second option with an interface changes your Pol class
completely and I am not sure if this is acceptable for you.
´
public class Bird {
private float x;
private float y;
private float size;
public Bird(float x, float y, float size) {
//set your members here
}
public Float getX() {
return this.x;
}
public Float getY() {
return this.y;
}
public Float getSize() {
return this.size;
}
}
´
Then the Pol class
´
public class Pol {
private final List<Supplier<Float>> inputs;
public Pol(List<Supplier<Float>> inputs) {
this.inputs = inputs;
}
public Float call(int index) {
return this.inputs.get(index).get();
}
}
´
And your main should look like
´
public static int main(String[] args) {
Bird bird = new Bird(1.0f, 1.0f, 2.5f);
Pol pol = new Pol(Arrays.asList(bird::getX,
bird::getY, bird::getSize));
Float birdsSize = pol.call(2);
return 0;
}
´
Related
Here's the code
class TwoD {
int x, y;
public TwoD(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class ThreeD extends TwoD {
int z;
public ThreeD(int x, int y, int z) {
super(x, y);
this.z = z;
}
}
class FourD extends ThreeD {
int t;
public FourD(int x, int y, int z, int t) {
super(x, y, z);
this.t = t;
}
}
class coords<T extends TwoD> {
T cordinates;
public coords(T cordinates) {
super();
this.cordinates = cordinates;
}
static void show(coords<? super ThreeD> c) {}
}
public class mainX {
public static void main(String a[]) {
FourD fourD = new FourD(1, 2,3,4);
coords check = new coords(fourD);
coords.show(check);
TwoD twoD = new TwoD(1, 2);
coords check1 = new coords(twoD);
coords.show(check1);
// How this program runs fine with the child and parent subclass objects in show method?
}
}
The method
static void show(coords c)
should only allow Parent class objects ? Why is it allowing child class objects also?
How this program runs fine with the child and parent subhclass objects in show method?
I am confused!
As mentioned by #Thomas in the comments, you're using raw types for your coords. (I could go into detail, but the linked answer explains everything very clearly. Your use case is mainly mentioned in the sections How's a raw type different from using <?> as a type parameter? and A raw type is the erasure of that type.)
If you'd change:
coords check = new coords(fourD);
...
coords check1 = new coords(twoD);
To:
coords<FourD> check = new coords<>(fourD);
...
coords<TwoD> check1 = new coords<>(twoD);
You would get the error you'd expect:
error: incompatible types: coords<TwoD> cannot be converted to coords<? extends ThreeD>
coords.show(check1);
^
PS/off-topic: Class coords should be with a capital C (thus Coords) when following Java's code standards.
I'm writing a game which contains elevators as an obstacle. An elevator spawns either left or right of the screen and has a random chance to be an ascending elevator or a descending elevator. It looks like this:
public class Elevator extends WorldObject {
public static boolean ascending;
public Elevator(int screenHeight, int xPos) {
super(xPos, screenHeight, 0, 0);
ascending = new Random().nextBoolean();
}
static public boolean isAscending(){
return ascending;
}
}
WorldObject from which it extends looks like this:
public class WorldObject {
protected float posX;
protected float posY;
protected float velX, velY;
public float getPosX() {
return posX;
}
public void setPosX(float posX) {
this.posX = posX;
}
public float getPosY() {
return posY;
}
public void setPosY(float posY) {
this.posY = posY;
}
public float getVelX() {
return velX;
}
public void setVelX(float velX) {
this.velX = velX;
}
public float getVelY() {
return velY;
}
public void setVelY(float velY) {
this.velY = velY;
}
public WorldObject(float posX, float posY, float velX, float velY) {
this.posX = posX;
this.posY = posY;
this.velX = velX;
this.velY = velY;
}
}
Every 5 seconds an elevator will be created and added to an ArrayList of Elevators like so:
if (timeToElevator > 5.0f) {
timeToElevator = 0;
Elevator elevator = new Elevator((int) screenHeight, (int) generateElevatorXPos());
Sprite eSprite = new Sprite(elevatorTexture);
eSprite.setOrigin(0, 0);
elevators.add(elevator);
elevatorSprites.add(eSprite);
}
I then check for collisions in each elevator with the player, remove it if it goes out of bounds and if neither of these happen I update the position of the elevator object:
public static void calculateElevatorCollisions() {
int counter = 0;
for (Iterator<Elevator> i = elevators.iterator(); i.hasNext(); ) {
Elevator item = i.next();
if (item.getPosY() < -100) {
//remove elevator
} else if (..collision..) {
//collision
} else {
item.setVelY(item.isAscending() ? -5 : 5);
item.setPosY(item.getVelY() + item.getPosY());
elevatorSprites.get(counter).setPosition(item.getPosX(),
item.getPosY());
counter++;
}
My issue is whenever a new Elevator is created all current Elevators change their direction to the direction of the new Elevator. So suppose I have two ascending elevators being drawn, whenever my third elevator is created to be descending, the other two previously ascending elevators now ascend!
What's causing this?
This is your problem:
public static boolean ascending;
^^^^^^
static means "This is a class field that is shared by all objects". So if you changed the field from one object, it will be noticed across all objects of that type.
Removing it to make ascending an instance field means that each instance of Elevator will have its own copy which it can modify by itself without changing other instances' copy.
Change
public static boolean ascending;
To
public boolean ascending;
When you set a variable as static it is a class variable, not an instance variable. Class variables are variables that are shared across all instances of an object, whereas instance variables are specific to that instance of the object.
As I can't comment yet (rep), I want to make another note:
You are practicing encapsulation using the getter for ascending, isAscending(); however, the field you are encapsulating is public, making it accessible from all scopes.
It's good practice to keep encapsulated fields private.
Also, it seems as if everyone is only stating that the field be changed to a non-static variable; however, the method is still static, even though it is actually an instance method as well!
Resulting changes needed:
public static boolean ascending;
becomes
private boolean ascending;
...and...
static public boolean isAscending()
becomes
public boolean isAscending()
I am trying to understand extending inner classes in Java. I have read around but nothing I found quite answers my question. So here goes...
I have...
public class Pie{
protected Slice[] slices;
// Pie constructor
public Pie(int n){
sliceGenerator(n)
}
private void sliceGenerator(int n){
slices = new Slice[n];
final float sweepAngle = 360.0f/(float)n;
float startAngle = 0;
for (int i=0;i<n;i++){
slices[i] = new Slice(startAngle);
startAngle += sweepAngle;
}
}
#Override
public String toString(){
for (Slice s:slices){
s.toString();
}
}
// Inner class...
public class Slice{
public Slice(float startAngle){
//set some private fields based on startAngle and generic pie
}
#Override
public String toString(){
return **string based on private fields**
}
}
}
Then I extend this...
public class ApplePie extends Pie{
protected Slice[] slices;
// Apple Pie constructor
public ApplePie(int n){
super(n);
}
// Inner class...
public class Slice extends Pie.Slice{
public Slice(float startAngle){
super(startAngle);
//set some **additional** private fields based on startAngle **specific to apple pie** appleness or something
}
#Override
public String toString(){
return **string based on apple pie specific private fields**
}
}
}
Now, when I make an Apple pie and call its toString method, like so...
ApplePie ap = new ApplePie(8);
System.out.println(ap.toString());
I do not get information about the apple pie slices, but information about the pie slices. It ignores my toString override, or more likely ignores my apple pie Slice. How can I arrange it such that apple pie slices refer to ApplePie?
Any help much appreciated! Sorry for pie references - it is the actual class I am working with...
I've changed your code to meet your requirements.
Your super class Pie is about to create a new instance of Slice, but the child class ApplePie's Slice does not override the Slice method of its super class'.
I added the functions below to enable the child class to create its own Slice.
protected void newSliceArray(int n) {
slices = new Slice[n];
}
protected Slice newSlice(float startAngle) {
return new Slice(startAngle);
}
Pie.java:
public class Pie {
private int a = 1;
protected Slice[] slices;
// Pie constructor
public Pie(int n) {
sliceGenerator(n);
}
private void sliceGenerator(int n) {
newSliceArray(n);
final float sweepAngle = 360.0f / n;
float startAngle = 0;
for (int i = 0; i < n; i++) {
slices[i] = newSlice(startAngle);
startAngle += sweepAngle;
}
}
protected void newSliceArray(int n) {
slices = new Slice[n];
}
protected Slice newSlice(float startAngle) {
return new Slice(startAngle);
}
#Override
public String toString() {
String t = "";
for (Slice s : slices) {
t += s.toString();
}
return t;
}
// Inner class...
public class Slice {
public Slice(float startAngle) {
// set some private fields based on startAngle and generic pie
}
#Override
public String toString() {
return "" + a;
}
}
}
ApplePie.java:
public class ApplePie extends Pie {
private int b = 2;
// protected Slice[] slices;
// Apple Pie constructor
public ApplePie(int n) {
super(n);
}
protected void newSliceArray(int n) {
slices = new Slice[n];
}
protected Slice newSlice(float startAngle) {
return new Slice(startAngle);
}
// Inner class...
public class Slice extends Pie.Slice {
public Slice(float startAngle) {
super(startAngle);
// set some **additional** private fields based on startAngle **specific to apple pie**
// appleness or something
}
#Override
public String toString() {
return b + "";
}
}
}
Test:
public static void main(String[] args) {
ApplePie ap = new ApplePie(8);
System.out.println(ap.toString());
}
The code will print 22222222
In your superclass, you are creating and storing Pie.Slice objects:
private void sliceGenerator(int n){
slices = new Slice[n];
final float sweepAngle = 360.0f/(float)n;
float startAngle = 0;
for (int i=0;i<n;i++){
slices[i] = new Slice(startAngle);
startAngle += sweepAngle;
}
}
These are the same objects being used by Pie.toString (which ApplePie doesn't override by the way).
Extending Pie with ApplePie and extending Pie.Slice with ApplePie.Slice doesn't change this. The new Slice(startAngle) in the above code does not magically switch to instantiating something different.
Aside from that, your Pie.toString() isn't returning anything - it shouldn't even compile:
#Override
public String toString(){
for (Slice s:slices){
s.toString();
}
}
I'm guessing you want to return a String representing all the slices. This would be a quick solution for example:
#Override
public String toString() {
return Arrays.toString(slices);
}
(Arrays.toString is just a utility method to get a String representing of an array.)
The answer lies within your program. When you instantiate Slice class, it gives call to the super class and invokes sliceGenerator. This method internally creates instances of Pie.Slice and not ApplePie.Slice. To get around this, make sliceGenerator method protected and override it in Apple.Slice class. Create the instances of Apple.Slice and it should work.
There is an example of "Implementing an Interface" in Java tutorial. I have repeated this example but it doesn't work. NetBeans shows the mistake on te left of RectanglePlus class declaration. And mistake is:
rectangleplus.RectanglePlus is not abstract and does not override
abstract method isLargerThan(rectangleplus.Relatable) in
rectangleplus.Relatable
I did the same as written in tutorial. Why it shows the mistake? Here is my implementation of the project.
The name of the project is RectanglePlus.
The name of the package is rectangleplus.
1st file in the project is Interface Relatable:
package rectangleplus;
public interface Relatable {
int isLarger(Relatable other);
}
2nd file in the project is Main Class RectanglePlus with helper class Point:
package rectangleplus;
public class RectanglePlus implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing
// the area of the rectangle
public int getArea() {
return width * height;
}
// a method required to implement
// the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
public static void main(String[] args) {
// TODO code application logic here
}
}
class Point {
int top;
int left;
int x;
int y;
public Point(int t, int l) {
top = t;
left = l;
}
}
Why there is nothing said about abstraction in the tutorial example? Should the tutorial example work without mitakes?
Thank you.
In the interface, you declare the method isLarger but in the class you declare isLargerThan Change one to the other name and it will go fine.
You're not correctly implementing the isLarger() method in the Relatable interface. Rename the isLargerThan(Relatable other) method so it looks like this:
#Override
int isLarger(Relatable other) {
}
It's a good idea to use the #Override annotation, it allows you to catch errors like the one in the question.
I am trying to run the following simple code,
public abstract class Shape{
abstract double area();
abstract double circumference();
public void show()
{
System.out.println("Area = "+area());
System.out.println("Circumference = "+circumference());
}
}
public class Circle extends Shape{
double r;
public double area()
{
return 3.14*r*r;
}
double circumference()
{
return 2*3.14*r;
}
Circle(double radius)
{
r=radius;
}
}
public class Rectangle extends Shape{
double x,y;
double area()
{
return x*y;
}
double circumference()
{
return 2*(x+y);
}
Rectangle(double length, double width)
{
x = length;
y = width;
}
}
public class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
But I keep getting identifier expected error from Java compiler. What am I doing wrong. Everything is public and there seems to be no syntax error. Please help.
This is the problem:
class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Your final statement doesn't declare a variable - it's just a statement. That needs to belong in an initializer block, constructor or method. For example:
public class Geometry {
public static void showCircle() {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
}
Note that this has nothing to do with inheritance - this code will give the same problem:
class Test {
System.out.println("Oops");
}
Your call to r.show(); is not in a code block. I suspect you intended to place this is a main method
public static void main(String... args) {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Add the main method:
public class Geometry
{
public static void main(String[] args) {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
}