alb85
November 10, 2020, 2:06pm
1
Hello everybody!
I think there is a problem in Processing with the method newInstance().
If I run this simple example:
void setup(){
try{
Test t = Test.class.newInstance();
}catch(Exception e){
e.printStackTrace();
}
}
void draw(){
}
class Test {
public Test() {
}
}
I receive the following error:
ava.lang.InstantiationException: sketch_201110a$Test
at java.lang.Class.newInstance(Class.java:427)
Do you have any ideas?
Many thanks.
Alberto
Chrisir
November 10, 2020, 2:48pm
2
Hello and welcome to the forum!
Great to have you here!
That’s how I’d do it.
Read more here: https://www.processing.org/tutorials/objects/
Warm regards,
Chrisir
Test t;
void setup() {
size(600, 600);
t = new Test();
}
void draw() {
//
}
// ===============================================================
class Test {
//
Test() {
}
//
}//class
alb85
November 10, 2020, 3:59pm
3
Yes. That is the “classic” way to do it. However, there are cases in which you have access only to the interface of a class, and the only way to instantiate the class is using the method newInstance.
In Java the piece of code that I posted works…
1 Like
Hi @alb85 ,
Not sure if this is what you are looking for,
This case implements an interface and a class is then defined and used. To create a new instance of a class Test, call Test_name = new Test();
interface Dot {
void move();
void display();
}
class CircleDot implements Dot {
float x = 50;
float y = 50;
void move() {
x = x + random(-1, 1);
}
void display() {
ellipse(x, y, 16, 16);
}
}
class SquareDot implements Dot {
float x = 50;
float y = 50;
void move() {
y = y + random(-1, 1);
}
void display() {
rect(x, y, 16, 16);
}
}
SquareDot sq;
void setup() {
size(100, 100);
sq = new SquareDot();
}
void draw() {
sq.move();
sq.display();
}
1 Like