using System.IO;public class Father
{
protected string test()//如果换成public就可以了
{
return "Father";
}
}class Child: Father
{
public static void Main()
{
Child c = new Child();
Father f =
(Father)c; System.Console.WriteLine(f.test());//问题出现在这里,我以为在子类里面放温父类的public或者protected应该都是一样的
}
}
{
protected string test()//如果换成public就可以了
{
return "Father";
}
}class Child: Father
{
public static void Main()
{
Child c = new Child();
Father f =
(Father)c; System.Console.WriteLine(f.test());//问题出现在这里,我以为在子类里面放温父类的public或者protected应该都是一样的
}
}
System.Console.WriteLine(test());
直接调用继承的方法
比较 base.Test()
你也可以用左手写字,但你不能用你爸的左手写字你爸有个盖章的public方法,任何人只要拿到图章,就可以盖章
你的这种已经不是在子类里面访问了..已经是一个新的实例,而不是在字类中了...谢谢你的回答,不过我想就算是一个新的实例,但是child是继承自father类,所以新的实例应该能访问father类的protected成员的,我是这样认为的不知道对不对?
所以你的想法是错的.你在Main 中实例化一个 Child 类,你应该也清楚这个类只是属于 Main ,而不属于 Child 吧?
说的有点乱,体会前面的那句话就可以了.
还是有个地方没弄没白,你的意思是否main方法只能访问这些类的public方法?
{
protected string test()//如果换成public就可以了
{
return "Father";
}
}class Child: Father
{
private string test2()
{
return "Child";
} public static void Main()
{
Child c = new Child();
System.Console.WriteLine(c.test2());//可以访问private方法 Father f =
(Father)c; System.Console.WriteLine(f.test());//问题出现在这里,我以为在子类里面放温父类的public或者protected应该都是一样的
}
}
f是强制转换为Father对象,类型变了但引用并没有变,还是原来的Child对象;
而f.test()调用的是本身的方法,而不是父类的
但实际上本身并不包含此方法调用继承的方法,是要来自父类的
比如你将一个类实例化后就不能使用私有成员了;子类实例化后,父类的protected同样不能使用。所以结合你的例子:using System.IO;
public class Father
{
protected string test()//如果换成public就可以了
{
return "Father";
}
}class Child: Father
{
private void Print()
{
string ss=Test();//这样就可以访问
}
public static void Main()
{
Child c = new Child();
Father f = (Father)c;
System.Console.WriteLine(f.test());//问题出现在这里}
}
}
private 限定的方法是否也不能够通过实例对象访问了?
class Father
{
...
}
class Child:Father
{
...
}class test
{
static void Main()
{
Child c=new Child();
Father f=(Father)c;
System.Console.WriteLine(f.test());
}
}