Calling Method of class within it - c#-4.0

// What is the technical reason behind this scenarios..?

You're trying to use a statement other than a declaration directly inside the class - rather than within a method. When did you expect the method to get called?
Basically all you can have directly within a type is a bunch of declarations - methods, variables, constructors, events, nested types etc. Method calls (or any other statements) which aren't part of a declaration have to be written within methods, constructors etc.

Method call statement can not be part of a class declaration, but only within Function members declarations scope, such as Methods, Properties, Constructors etc.
For example:
public class ExampleClass
{
private void SayHelloWorld()
{
Console.Writeline("Hello World!");
}
public void CallSayHelloWorldMethod()
{
this.SayHelloWorld();
}
}
At the above example you can see that I call the SayHelloWorld method within the CallSayHelloWorldMethod metod.
Update:
The closest thing I can think of in your case is to use the class's constructor where your method call will be executed as soon as you'll instantiate your class:
public class ExampleClass
{
//The class constructor
public ExampleClass()
{
this.SayHelloWorld();
}
private void SayHelloWorld()
{
Console.Writeline("Hello World!");
}
}
And when you instantiating it, it will be immediately called:
//Your method call will be executed here
ExampleClass exampleClass = new ExampleClass();

You have a few problems... This won't even compile as you are trying to call the method obj.m1() in the class definition.
A obj = new A();
obj.m1(); // Why this code wont work??? --> This must be inside a method
When you create an instance of a class it will create a new member variable called obj which is an instance of A --> A obj = newA() above;
You will now be able to call obj's methods as in your second example.
Also, in order to get this to compile you will need to fix the m2 method:
public void m2() { //--> should have a curly brace
obj.m1(); // But This will work.
}

Related

why constructor is not called for static objects created inside a class?

#include<iostream>
class A
{
public:
int x;
A()
{
x=4;
std::cout<<"inside A constructor"<<std::endl;
}
void function()
{
std::cout<<"inside function"<<x<<std::endl;
}
};
class B
{
public:
B()
{
std::cout<<"inside b constructor"<<std::endl;
obj.function();
}
private:
static A obj;
};
B b;
A B::obj;
int main()
{
}
In the above code obj.function(); is called for the first time it knows that obj is a member of class A,since initialization of static objects done during the compile time itself,but why not the constructor is called.
The constructor is called only after control hits the line A B::obj;
if i declare the static A obj; outside class B then the constructor is called.
why the behavior is different for both?
B b;
when the above line executes,the constructor of B is called first.
so "inside b constructor" is printed first.
Then when control reaches obj.function(); the obj is already initialized by the
compiler since it is a static type of object.
so obj.function() is called without any problem and "inside function" is printed.
Now the control reaches A B::obj; definition of static object.
so constructor of A is called and "inside A constructor" is printed.
note:
only when the definition of static object is called the constructor is used.
so only we donot see constructor of A when static A obj; is declared inside the class B.
Another question may arise why declaration is only made for static variables inside a class and definition needs to be called explicitly outside class?
The answer is the definition of class can be made inside a header file and this header file can be included in multiple *.cpp files.
so,If the definition is also present inside the class then the static variable will have multiple definitions which will cause erroe.
Inorder to avoid the above the definition for static members outside a class is made exclusively.

Handle function calls on a class in Node.JS

Assuming that you have a class
class MyClass {
world() {
console.log("hello world");
}
}
I can run the method similar to the following:
var hello = new MyClass();
hello.world();
# outputs: hello world
Is there a way to handle direct function calls on an object? For example:
hello();
Returns: TypeError: hello is not a function.
Can I make this call a default function? For example, similar to PHP's invoke function ...
We can only make something callable in JavaScript if that thing is an object which, at some point, delegates to Function.prototype. Therefore, our class will need to extend Function or extend from a class which extends Function. We also need to be able to access instance variables from our class object (in order to call invoke()), so it needs to be bound to itself. This binding can only happen in the constructor.
Since our class will inherit from Function, we need to call super before being able to use this . However, the Function constructor actually takes a code string, which we won't have, because we want to be able to set invoke later on. So we'll need to extend Function in a different class which will be the parent class to our class and which will do the work of setting the prototype of our dummy function (which we need in order to be able to call the returned object). Bringing all of this together, we get:
class ExtensibleFunction extends Function {
constructor(f) {
// our link to Function is what makes this callable,
// however, we want to be able to access the methods from our class
// so we need to set the prototype to our class's prototype.
return Object.setPrototypeOf(f, new.target.prototype);
}
}
class MyClass extends ExtensibleFunction {
constructor() {
// we build an ExtensibleFunction which accesses
// the late-bound invoke method
super(function() { return this.invoke(); });
return this.bind(this); // and bind our instance
// so we have access to instance values.
}
invoke() {
console.log("Hello, world!");
}
}
x = new MyClass();
x(); //prints "Hello, world!"
I mostly adapted the techniques found in this answer in order to do this.
An interesting aspect of using this technique is that you could name MyClass something like Callable and remove the invoke method - then any class which extends Callable would become callable as long as it had an invoke() method. In fact...
class ExtensibleFunction extends Function {
constructor(f) {
// our link to Function is what makes this callable,
// however, we want to be able to access the methods from our class
// so we need to set the prototype to our class's prototype.
return Object.setPrototypeOf(f, new.target.prototype);
}
}
class Callable extends ExtensibleFunction {
constructor() {
// we build an ExtensibleFunction which accesses
// the late-bound invoke method
super(function() { return this.invoke(); });
return this.bind(this); // and bind our instance
// so we have access to instance values.
}
}
class CallableHello extends Callable {
invoke() {
console.log("Hello, world!");
}
}
class CallableBye extends Callable {
invoke() {
console.log("Goodbye cruel world!");
}
}
x = new CallableHello();
x(); //prints "Hello, world!"
y = new CallableBye();
y(); //prints "Goodbye cruel world!"
(Of course, you could get the same effect by setting properties on function objects, but this is more consistent I guess)

Why doesn't a Groovy closure have access to injected class member?

We are using Groovy and Guice on a project and I came across the following error:
groovy.lang.MissingPropertyException: No such property: myService for class: com.me.api.services.SomeService$$EnhancerByGuice$$536bdaec
Took a bit to figure out, but it was because I was referencing a private class member, that was injected, inside of a closure. Can anyone shed any light as to why this happens?
Furthermore, is there any better way of doing this?
Here is a snippet of what the class looks like:
import javax.inject.Inject
import javax.inject.Singleton
#Singleton
class MyService extends BaseService<Thing> {
#Inject
private ThingDao thingDao
#Inject
private OtherService<Thing> otherService
#Override
List<Thing> findAll() {
List<Thing> things = this.dao.findAll()
things.each {
//Note: This doesn't work!
otherService.doSomething()
}
things
}
I either have to use a standard for loop or not use the injected member which then tends to lead to code duplication.
TLDR;
Either declare otherService public (remove private modifier) or add a getter OtherService<Thing> getOtherService(){otherService}
If you absolutely want to avoid exposing the field through a property, you can do the following trick: create a local variable outside the Closure scope that references your service:
OtherService<Thing> otherService=this.otherService
things.each {
//Note: This will work! Because now there is a local variable in the scope.
//This is handled by normal anonymous inner class mechanisms in the JVM.
otherService.doSomething()
}
Explanation
Under the hood, your closure is an object of an anonymous class, not the object that has your private field, otherService.
This means that it can't resolve a direct reference to the field. Accessing a symbol inside the closure will first look at local variables, and if no match is found, the getProperty() method in Closure will be called to find a property, depending on the resolution strategy that you defined. By default, this is OWNER_FIRST.
If you look the code of Closure#getProperty:
switch(resolveStrategy) {
case DELEGATE_FIRST:
return getPropertyDelegateFirst(property);
case DELEGATE_ONLY:
return InvokerHelper.getProperty(this.delegate, property);
case OWNER_ONLY:
return InvokerHelper.getProperty(this.owner, property);
case TO_SELF:
return super.getProperty(property);
default:
return getPropertyOwnerFirst(property);
}
You see that the owner, delegate and declaring objects need to have matching properties.
In groovy, if you declare a field private, you won't get auto-generated accessor methods, so no properties will be publicly exposed for outside objects.

groovy: variable scope in closures in the super class (MissingPropertyException)

I have the impression that closures run as the actual class being called (instead of the implementing super class) and thus break when some variables are not visible (e.g. private in the super class).
For example
package comp.ds.GenericTest2
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
this.add(obj)
}
}
b = new ClosureScopeD()
// THIS THROWS groovy.lang.MissingPropertyException: No such property: accessThisPrivateVariable for class: comp.ds.GenericTest2.ClosureScopeD
b.doSomething("abc")
The last line throws a MissingPropertyException: the child class calls the "add" method of the super class, which executes the "each" closure, which uses the "accessThisPrivateVariable".
I am new to groovy, so I think there must be an easy way to do this, because otherwise it seems that closures completely break the encapsulation of the private implementation done in the super class ... this seems to be a very common need (super class implementation referencing its own private variables)
I am using groovy 2.1.3
I found this to be a good reference describing how Groovy variable scopes work and applies to your situation: Closure in groovy cannot use private field when called from extending class
From the above link, I realized that since you have declared accessThisPrivateVariable as private, Groovy would not auto-generate a getter/setter for the variable. Remember, even in Java, private variables are not accessible directly by sub-classes.
Changing your code to explicitly add the getter/setters, solved the issue:
package com.test
import groovy.transform.CompileStatic
#CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
int getAccessThisPrivateVariable() { accessThisPrivateVariable }
void setAccessThisPrivateVariable(int value ){this.accessThisPrivateVariable = value}
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
super.add(obj)
}
}
b = new ClosureScopeD()
b.doSomething("abc")
There is a simpler way, just make the access modifier (should rename the property really) to protected, so the sub-class has access to the property.. problem solved.
protected int accessThisProtectedVariable
To clarify on your statement of concern that Groovy possibly has broken encapsulation: rest assured it hasn't.
By declaring a field as private, Groovy is preserving encapsulation by intentionally suspending automatic generation of the public getter/setter. Once private, you are now responsible and in full control of how or if there is a way for sub-classes (protected) or all classes of objects (public) to gain access to the field by explicitly adding methods - if that makes sense.
Remember that by convention, Groovy ALWAYS calls a getter or setter when your codes references the field. So, a statement like:
def f = obj.someField
will actually invoke the obj.getSomeField() method.
Likewise:
obj.someField = 5
will invoke the obj.setSomeField(5) method.

non-static variable this cannot be referenced from a static context

I'm working with java me. I tried to switch to a displayable(form2) in Second.java from an okCommand in another displayble(form1) in First.java (see my previous question on that).
I got an error non-static method getForm2() cannot be referenced from a static context. I had to add the word static to form2 declaration and also at the getForm2 method in Second.java before it could work.
Problem now is that a backCommand in form2 can't switch back to form1 in First.java and it pops up the error non-static variable this cannot be referenced from a static context.
I paused and took some time to refresh myself on the language fundamentals on how the static keyword is used and I got to know that a static method is a class method and a non-static method is an instance method and that a non-static cannot call a static method unless an instance of the non-static method is created and also that a static method can't call a non-static method.
I'm really not understanding the implementation as I should, and I'd appreciate some clarification using my example above.
Here's the source below from Second.java the error is coming from form2.setCommandListener(this);
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(this);
}
return form2;
You have a static method, but are using this. But this doesn't exist. It would normally reference to an instance of the class, but you don't have one here.
If your method wasn't static and you instantiated an instance of this class then this would work.
e.g.
Second s = new Second();
Form f = s.getForm2(); // if this method wasn't static
Making that method static means little more than namespacing. There isn't an associated instance and no this.
There are couple options. First is to create a static instance of Second and use it in the getForm2:
//...
// static instance
private static Second instance = new Second(/* put constructor arguments here, if any */);
//...
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(instance); // --> replace "this" with "instance"
}
//...
From the issues you describe though, I would prefer another option - returning to design you had in previous question and use an instance of Second as an argument passed via constructor of First.
Your First.java would then have lines like:
//...
private final Second second; // instance needed for commandAction
//...
First(Second second) { // constructor with parameter
this.second = second; // save the parameter
//...
}
Then, commandAction method in First.java could use code like:
switchDisplayable(null, second.getSecondForm());
// instead of Second.getSecondForm()

Resources