我了解到接口也用于封装方法,但在下面的代码中通过将ojb
强制转换为MainClass
我可以从Mainclass
访问其他方法,我没有声明在接口中,现在封装发生的地方。
class Program
{
static void Main(string[] args)
{
IInterface obj = new MainClass();
Console.WriteLine(((MainClass)obj).FullName()+" " +obj.LastName());
Console.WriteLine(((MainClass)obj).SayHello());
Console.ReadKey();
}
}
public interface IInterface
{
string LastName();
}
public class MainClass:IInterface
{
public string FullName()
{
return "Raman Singh";
}
public string SayHello()
{
return "Hello Sir111";
}
public string LastName()
{
return "Chauhan";
}
}
答案 0 :(得分:4)
您在interface
和encapsulation
之间感到困惑。这不是接口的用途。
An interface contains definitions for a group of related functionalities that a class or a struct can implement. By using interfaces, you can, for example, include behavior from multiple sources in a class.
而
Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing.
如你所说的那样,一旦你施放,你实际上正在MainClass
的{{1}}实例中持有obj
个实例。因为你实际上是使用`new MainClass();'来初始化它。这将调用MainClass的构造函数来初始化obj。这就是为什么你可以访问其他方法。
答案 1 :(得分:1)
首先你提到“接口也用于封装”这是错误的。接口用于抽象。
在您的代码中,您创建了类的对象,并在调用方法时将其强制转换。现在,如果您的方法是公开的,那么通过将其投射到您的班级,您显然可以访问它。
只有当您的客户端不了解您的类的具体实现时,您才可以通过抽象隐藏其他方法,并且必须通过接口访问您的方法。然后,客户端可以访问在接口中声明的方法。
尝试用简单的语言回答您的评论。通过声明
IInterface obj = new MainClass();
您正在创建MainClass类型的对象。这将创建新实例并返回其对IInterface类型的变量的引用,但是在运行时。
现在,当您分配对接口类型的引用时,虽然该对象是MainClass,但您使用接口变量访问它。但是接口不知道你的类中没有从该接口继承的其他方法。因此,无需在运行时讨论驻留在堆中的对象,因为即使编译器也不允许您访问接口变量不知道的类的其他方法。
您只能调用其他方法,因为您再次将接口变量强制转换为Class类型。希望它让事情变得容易理解。
答案 2 :(得分:0)
将对象转换为MainClass时,对象引用从IInterface更改为MainClass。因此,所有MainClasses Mehtod都可用,因为所述方法的可见性取决于对象引用。 如果你不将你的对象转换为MainClass并让它的引用是IInterface类型,那么只有LastName方法可见。
答案 3 :(得分:0)
您的代码与实例字段的编码相同,而不是接口,因为强制转换(MainClass)obj正在将其更改回它。