In Java, static methods and variables can be accessed through object reference, like in the program below, which is working absolutely fine:
//StaticDemo.java
class StaticVerifier{
private int a,b;
public StaticVerifier(int a,int b){
this.a = a;
this.b = b;
System.out.println("Values are "+this.a+" "+this.b);
}
public static void takeAway(){
System.out.println("This is a static method...");
}
}
public class StaticDemo{
public static void main(String[] args){
StaticVerifier sv = new StaticVerifier(3,4);
sv.takeAway();
}
}
But when I tried the same code converted in C# its not allowing the object to access the static method and giving compile time error. See the code and associated error below:
//StaticDemo.cs
using System;
public class StaticVerifier{
private int a,b;
public StaticVerifier(int a,int b){
this.a = a;
this.b = b;
Console.WriteLine("Values are "+this.a+" "+this.b);
}
public static void takeAway(){
Console.WriteLine("This is a static method...");
}
}
public class StaticDemo{
public static void Main(string[] args){
StaticVerifier sv = new StaticVerifier(3,4);
sv.takeAway(); // here, unable to access static methods, but can use classname rather than objectname !
}
}
Errors:
StaticDemo.cs(17,3): error CS0176: Member 'StaticVerifier.takeAway()' cannot be
accessed with an instance reference; qualify it with a type name instead
StaticDemo.cs(10,21): (Location of symbol related to previous error)
Can anybody tell me why C# don't have this accessibility and Java has, though both are based on object oriented paradigm?(I mostly mean "why the vendors had made it so?")