There is a class lets say calculator which add some values
public class Calculator
{
public int Addition(int a, int b)
{....}
public int Addition2(int a, int b, int c)
{....}
public int Addition3(int a, int b,int c, int d)
{....}
}
in Main:
Calculator calc= new Calculator();
// create object
how do I create object or objects so that I can restrict object access to specific functions only.
Ex: obj1 has access to Addition only, obj2 has access to Addition & Addition2 and so on. Means define specific objects access to class functions.
Lets
CodePudding user response:
Interface is a powerful tool to publish certain members while others can remain hidden.
public interface IAddition
{
public int Addition(int a, int b)
}
public interface IAddition2
{
public int Addition2(int a, int b, int c)
}
public interface IAddition3
{
public int Addition3(int a, int b,int c, int d)
}
public class Calculator : IAddition, IAddition2, IAddition3
{
public int Addition(int a, int b)
public int Addition2(int a, int b, int c)
public int Addition3(int a, int b, int c, int d)
}
IAddition addition = new Calculator();
IAddition2 addition2 = new Calculator();
IAddition3 addition3 = new Calculator();
CodePudding user response:
public interface ICalculator
{
int Addition(int a, int b);
}
public interface ICalculator1 : ICalculator
{
int Addition2(int a, int b, int c);
}
public interface ICalculator2 : ICalculator1
{
int Addition3(int a, int b, int c, int d);
}
public class Calculator : ICalculator2
{
public int Addition(int a, int b)
{ return 1; }
public int Addition2(int a, int b, int c)
{ return 1; }
public int Addition3(int a, int b, int c, int d)
{ return 1; }
}
Then in your main function:
static void Main(string[] args)
{
//Access to first func
ICalculator calculator = new Calculator();
calculator.Addition(1, 1);
//Access to first & second func
ICalculator1 calculator1 = new Calculator();
calculator1.Addition(1, 1);
calculator1.Addition2(1, 1, 1);
//Access to first & second & third func
ICalculator2 calculator2 = new Calculator();
calculator2.Addition(1, 1);
calculator2.Addition2(1, 1, 1);
calculator2.Addition3(1, 1, 1, 1);
}
CodePudding user response:
You can make Calculator
implement multiple interfaces
public class Calculator : IAddition1, IAddition2, IAddition3
{
public int Addition(int a, int b)
{....}
public int Addition2(int a, int b, int c)
{....}
public int Addition3(int a, int b, int c, int d)
{....}
}
interface IAddition1 {
int Addition(int a, int b)
}
interface IAddition2 {
int Addition(int a, int b, int c)
}
interface IAddition3 {
int Addition(int a, int b, int c, int d)
}
Then you can create it as
IAddition2 calc = new Calculator();
And it will only have int Addition2(int a, int b, int c)