I am trying to play around with class instantiation and this.
In the below example, the testresult class will be instantiated and stored.
this will be used to pass that class instance as a parameter to another class.
Is this proper usage of this as the class is instantiated elsewhere?
Not sure why I see error as "The constructor testfail(new Handler(){}) is undefined".
Code snippet:
public class testmain {
private testresult tr;
private testfunc tf;
public testmain() {
tr = new testresult();
tf = new testfunc(tr);
}
}
public class testfunc {
private testresult storeit;
public testfunc(testresult inst) {
storeit = inst;
}
// this will be running as seperate thread running forever.
}
public class testresult {
private testfail tp;
public void function() {
tp = new testfail(this); //----> error new Handler(){} undefined
}
}
public class testfail {
public testfail(testresult tr) {
///
}
}
Edit : The error due to inner class
public class testresult {
private testfail tp;
private class test {
public void function() {
tp = new testfail(this); ----> error
// new Handler(){} undefined
}
}
}
As written, your code will compile. Because testfail accepts an argument of testresult, using this will work, even though it's awkward and not something one normally sees.
Unless you overrode your testfail constructor by introducing another constructor that accepted a Handler as an argument, this compilation failure is expected.
As an example:
public class testfail {
public testfail(testresult tr) {
///
}
public testfail(Handler hr) {
}
}
Related
I read that it is not possible to create a subclass from a class whose constructor is private but weirdly I am able to do it, is there something more to this snippet?
Please someone provide an easy to understand & satisfactory explanation.
public class app {
public static void main(String[] args) {
app ref = new app();
myInheritedClass myVal = ref.new myInheritedClass(10);
myVal.show();
}
int myValue = 100;
class myClass {
int data;
private myClass(int data) {
this.data = data;
}
}
class myInheritedClass extends myClass {
public myInheritedClass(int data) {
super(data);
}
public void show() {
System.out.println(data);
}
}
}
I ran this snippet on https://www.compilejava.net/ and the output was 10.
Because your classes are both nested classes (in your case, specifically inner classes), which means they're both part of the containing class, and so have access to all private things in that containing class, including each other's private bits.
If they weren't nested classes, you wouldn't be able to access the superclass's private constructor in the subclass.
More about nested classes in the nested class tutorial on the Oracle Java site.
This compiles, because A and B are inner classes, which are nested classes (live copy):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
class A {
private A() {
}
}
class B extends A {
private B() {
super();
}
}
}
This compiles, because A and B are static nested classes (live copy):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
static class A {
private A() {
}
}
static class B extends A {
private B() {
super();
}
}
}
This does not compile because A's constructor is private; B cannot access it (I don't really need Example in this case, but I've included it in the two above, so for context...) (live copy):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
}
class A {
private A() {
}
}
class B extends A {
private B() {
super(); // COMPILATION FAILS HERE
}
}
I have some classes nested one in another
public abstract class I
{
public abstract int f();
}
public class J
{
private List<I> li;
public J(List<I> l)
{
li = l;
}
}
public class A // first class
{
private int x; // field of A
public class B extends J // second class
{
public B()
{
super(new ArrayList<I>() // super call
{{ // array initializer
add(new I() // third class
{
#Override
public int f()
{
return x; // <- here!!!
}
});
}});
}
}
}
Under these conditions, I get the error: "error: no enclosing instance of type A is in scope". Removing any element from this setup fixes this error. Also, taking x and saving it to another variable then using that variable also works.
What is happening here? It seems like a bug in a compiler for me.
It is not allowed to have 2 public classes in one Java File and file name should be same as public class name.
To experiment with your code I made a new Test class like this. I see no errors reported (using Java 8). Perhaps this is a build issue.
public class Test {
public abstract class I {
public abstract int f();
}
public class J {
private List<I> li;
public J(List<I> l) {
li = l;
}
}
public class A // first class
{
private int x; // field of A
public class B extends J // second class
{
public B() {
super(new ArrayList<I>() // super call
{
{ // array initializer
add(new I() // third class
{
#Override
public int f() {
return x; // <- here!!!
}
});
}
});
}
}
}
public void test() {
System.out.println("Hello");
}
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc="test">
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
//</editor-fold>
}
}
Java 7 also seems to accept this code.
I am reading Java 8 book, and it comes with a sample I reproduce:
#FunctionalInterface
public interface Action {
public void perform();
}
An Implementor:
public final class ActionImpl implements Action {
public ActionImpl() {
System.out.println("constructor[ActionIMPL]");
}
#Override
public void perform() {
System.out.println("perform method is called..");
}
}
A caller:
public final class MethodReferences {
private final Action action;
public MethodReferences(Action action) {
this.action = action;
}
public void execute() {
System.out.println("execute->called");
action.perform();
System.out.println("execute->exist");
}
public static void main(String[] args) {
MethodReferences clazz = new MethodReferences(new ActionImpl());
clazz.execute();
}
}
If this is called the following is print into the output:
constructor[ActionIMPL]
execute->called
perform method is called..
execute->exist
Everything is all right but if I use method references not perform message method is printed! Why is this, am I missing something?
If I use this code:
MethodReferences clazz = new MethodReferences(() -> new ActionImpl());
clazz.execute();
Or this code:
final MethodReferences clazz = new MethodReferences(ActionImpl::new);
This is printed:
execute->called
constructor[ActionIMPL]
execute->exist
No exception message or anything else is printed. I am using Java 8 1.8.25 64bit.
Update
For readers that are studying like me, this is the right running code.
I have created a class the caller.
Because I need to implement a empty method "perform from the Action functional interface" which I need to pass as parameter to class constructor MethodReference I reference the "constructor of the MethodReferenceCall which is a empty constructor" and I can use it.
public class MethodReferenceCall {
public MethodReferenceCall() {
System.out.println("MethodReferenceCall class constructor called");
}
public static void main(String[] args) {
MethodReferenceCall clazz = new MethodReferenceCall();
MethodReferences constructorCaller = new MethodReferences(MethodReferenceCall::new);
constructorCaller.execute();
}
}
This
MethodReferences clazz = new MethodReferences(() -> new ActionImpl());
does not use method reference, it uses a lambda expression. The functional interface is Action's
public void perform();
So
() -> new ActionImpl()
gets translated into something similar to
new Action() {
public void perform() {
new ActionImpl();
}
}
Similarly, in
MethodReferences clazz = new MethodReferences(ActionImpl::new);
the ActionImpl::new, which does use a constructor reference, is translated into something like
new Action() {
public void perform() {
new ActionImpl();
}
}
This ActionImpl::new does not invoke new ActionImpl(). It resolves to an instance of the expected type whose functional interface method is implemented as invoking that constructor.
i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));
I am new to Java and working in the Processing environment. I want to create a class that has a few objects in it, but I am getting an error when I try to construct those classes' object.
The bzaVertex is supposed to be an object within the bza object, but when I seemingly try to construct it, Processing says "The constructor sketch.BzaVertext(int) is undefined." I don't understand how Bza is getting its constructor called properly, but not the child object -- I seem to be calling them the same way?
I have this code all in the main class. I'm using Processing 2.0b7. What am I doing wrong?
Bza bza;
void setup() {
bza = new Bza();
}
public class BzaVertex {
public void BzaVertex(int d) {
}
}
public class Bza {
BzaVertex v1;
public void Bza() {
v1 = new BzaVertex(4);
}
}
constructors do not have a return type so you need to to remove the void from both of them
class BzaVertex {
public BzaVertex(int d) {
}
}
class Bza {
BzaVertex v1;
public Bza() {
v1 = new BzaVertex(4);
}
}
public class Main
{
public static void main(String[] args)
{
Bza bza;
bza = new Bza();
}
}
that should solve the error