Java program compilation failed - class

While studying interface I came along this weird behaviour
When I am running this
int num=20;
public void sound();
public void eat();
}
class Dog implements Animal{
public void sound(){
System.out.println("Wooof!!!!!!!");
}
public void eat(){
System.out.println("Food");
}
}
public class Main{
public static void main(String[]args){
Dog dog=new Dog();
dog.sound();
dog.eat();
System.out.println(Dog.num);
//System.out.println(Dog.num1);
}
}
It runs fine while If I declare a no static variable with same name i.e. num as of the one in interface like this
interface Animal{
int num=20;
public void sound();
public void eat();
}
class Dog implements Animal{
int num=10;
public void sound(){
System.out.println("Wooof!!!!!!!");
}
public void eat(){
System.out.println("Food");
}
}
public class Main{
public static void main(String[]args){
Dog dog=new Dog();
dog.sound();
dog.eat();
System.out.println(Dog.num);
//System.out.println(Dog.num1);
}
}
It gives this error Main.java:22: error: non-static variable num cannot be referenced from a static context
My question was since one from interface is static and is of class level why the child class i.e. Dog compilation fails when I declare a non static instance level variable.

The problem is your are trying to access Dog class into System.out.println(). Not the variable dog where the class has been initialized.
If variable num is not static is impossible to read it without initialize the class, so if you want to do Dog.num, that variable has to be static.
If you don't add the variable into Dog class, the value will be declared in the interface, but if the variable exists in the class, the compiler will try read that.

Related

Accessing private method from a static one

I'm trying to access a private method from a static one in the same class in Dart.
class MyClass{
void _initFunc() {
/// ...
}
static void info(){
if (condition){
_initFunc();
}
}
}
I got this error
Instance members can't be accessed from a static method.
Can you please explain me why, and how can i do. info() must be static, and _initFunc() must be private.
There is no "this" in a static method. So MyClass.info() doesn't have a "this" to call this._initFunc();
In Dart the static modifier on class members and methods makes them available without creating an instance of a class object. For example special constructors are static because you want to create a instance with them. Consider MyClass foo = MyClass.fromAnotherObject(bar); -> static MyClass fromAnotherObject(){} is static because you don't yet have a MyClass object to call it on.
In your example code, you could change _initFunc() to a public function (remove the "_") and either:
a) instantiate a MyClass object inside your static info() method and call initFunc()
class MyClass{
void initFunc() {
/// ...
}
static void info(){
if (condition){
MyClass myClass = MyClass();
myClass.initFunc();
}
}
}
OR
b) declare initFunc() also static and call it from info()
class MyClass{
static void initFunc() {
/// ...
}
static void info(){
if (condition){
MyClass.initFunc();
}
}
}

C# issue with class instantiation

I'm running a C# project on VS2019 with the following code structure:
In the Class1.cs file:
public class Class1
{
public class MyClass2 : Class2
{
...
}
private void RunAlgorithm<T>() where T : Class2, new()
{
T argInstance = new T();
...
}
static void Main(string[] args)
{
RunAlgorithm<MyClass2>();
}
}
In the Class2.cs file:
public class Class2
{
public Class2() { }
public string setParameters { get; set; }
}
I'm getting the following error for the line RunAlgorithm<MyClass2>();
'Class1.MyClass2' must be a non-abstract type with a public
parameterless constructor in order to use it as parameter 'T' in the
generic type or method 'Class1.RunAlgorithm()'
even if I change it to Public, the error persists
Well, minimally, it'll have to be protected so that MyClass can access it..
https://dotnetfiddle.net/XFeEdQ
public class Class1
{
class MyClass2 : Class2
{
}
private void RunAlgorithm<T>() where T : Class2, new()
{
T argInstance = new T();
}
public static void Main(string[] args)
{
new Class1().RunAlgorithm<MyClass2>();
}
}
public class Class2
{
protected Class2() { }
public string setParameters { get; set; }
}
So your "Class1.MyClass2
must have a public parameterless constructor" message is saying that your MyClass needs a constructor. Mine above has such a constructor even though it's not in the code; in the absence of the developer providing a constructor the compiler provides one that does nothing other than call the base parameterless constructor...
...which leads me to the next point; your MyClass2 extends Class2, and hence Class2's constructor needs to be accessible to it. While Class2's constructor is private, MyClass2's constructor can't call it. Every constructor on c# has to either call another constructor or a base constructor. If you don't specify which, the compiler will insert a call to base() for you, which will fail if the base constructor is inaccessible
For this all to work out you need a public parameterless constructor in MyClass2:
public MyClass2():base(){}
or without the base(compiler will add the base call)
or blank (compiler will add all of it)
and you need something that makes Class2's constructor accessible to MyClass2, ie declaring Class2's constructor as public or protected

Is there a way to tell the scala compiler to generate private methods when compiling anonymous scala functions?

I have this code in Foo.scala
object Foo extends App
{
def bar() = () => println("hello")
bar()()
}
If I run
scalac Foo.scala
I obtain three .class files:
Foo$.class
Foo$delayedInit$body.class
Foo.class
If then I run
javap 'Foo$.class'
I get on stdout
Compiled from "Foo.scala"
public final class Foo$ implements scala.App {
public static Foo$ MODULE$;
public static {};
public java.lang.String[] args();
public void delayedInit(scala.Function0<scala.runtime.BoxedUnit>);
public void main(java.lang.String[]);
public long executionStart();
public java.lang.String[] scala$App$$_args();
public void scala$App$$_args_$eq(java.lang.String[]);
public scala.collection.mutable.ListBuffer<scala.Function0<scala.runtime.BoxedUnit>> scala$App$$initCode();
public void scala$App$_setter_$executionStart_$eq(long);
public final void scala$App$_setter_$scala$App$$initCode_$eq(scala.collection.mutable.ListBuffer<scala.Function0<scala.runtime.BoxedUnit>>);
public scala.Function0<scala.runtime.BoxedUnit> bar();
public static final void $anonfun$bar$1();
public final void delayedEndpoint$Foo$1();
}
As you can see the lambda that is returned from the bar method is
compiled into public static final void $anonfun$bar$1();
I would like to be able to have all the lambda used in my scala code compiled as private method instead of public ones (it shouldn't be a problem when those functions are just local method variables, since they can only be accessed from within the method in which they are declared). Is there a way to achieve that?
P.S.
I'm asking because I'm using Scala to create Java EE's EJB classes and EJB classes used with no-interface view cannot have methods that are both public and final (it must be possible to instantiate a subclass that overrides all the public methods to create a proxy)

MEF Error when add item to list in constructor method

i write silverlight program very simple.i use Mef and WCF.
this code is MainPageViewModel class that included Commands and properties.
public List<NoOfStudentsDropDownItem> ListNoOfStudent{get;set;}
public MainPageViewModel()
{
InitializList();
}
private void InitializList()
{
ListNoOfStudent.Add(New NoOfStudentsDropDownItem(){DisplayText="1",NoOfStudent=-1});
ListNoOfStudent.Add(New NoOfStudentsDropDownItem(){DisplayText="5",NoOfStudent=5});
}
this is NoOfStudentsDropDownItem class;
public Class NoOfStudentsDropDownItem
{
public string DisplayText{get;set;}
public int NoofStudent{get;set}
}
this is part of App Class.
private void Application_Startup(object sender,StartupEventArgs e)
{
CompositionInitializer.SatisfyImports(this);
MainPage mainpage=new MainPage();
mainpage.DataContext=MainViewModel;
this.RootVisual=mainpage;
}
[Import]
public MainPageViewModel MainViewModel{get;set;}
i haven't error when commented InitializList method.i dont know cause.
You simply forgot to create the list. You declared a property for it, but it is never assigned so it will still be null when you call Add.

Testing mocked objects rhino mocks

I am new to RhinoMocks, and I am trying to write a test as shown
I have classes like these
public class A
{
public void methodA(){}
}
public class B
{
public void methodB(A a)
{
a.methodA();
}
}
And i am trying to test it like this
A a = MockRepository.GenerateMock<A>();
public void ShouldTest()
{
B b = new B();
b.methodB(a);
a.AssertWasCalled(x=>x.methodA());
a.VerifyAllExpectations();
}
But it is giving the error as shown:
System.InvalidOperationException : No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call.
How do I test methodB then?? Can someone help??
Rhino mock creates proxy class when you call MockRepository.Generate *** method. This means that it extends your type. If you don't declare any abstraction you cannot make any derivation which is essential in any mocking framework.
You can do two things
Create an interface (better design)
Make the member virtual (this will allow RhinoMocks to derive from your type and create a proxy for the virtual member
Sample code
public interface IA { void methodA();}
public class A:IA{public void methodA() { }}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
[TestFixture]
public class Bar
{
[Test]
public void BarTest()
{
//Arrange
var repo = MockRepository.GenerateMock<IA>();
//Act
B b = new B();
b.methodB(repo);
//Assert
repo.AssertWasCalled(a => a.methodA());
repo.VerifyAllExpectations();
}
}
You have concrete classes with no virtual methods and no interfaces. You can't mock anything.
Update:
Here's one way to do it:
public interface IA
{
void methodA();
}
public class A : IA
{
public void methodA(){}
}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
Then use
IA a = MockRepository.GenerateMock<IA>();