In: Computer Science
C# programming
Create a class called A with private integer field x, protected integer field y, public integer field z. Create a class B derived from class A with public integer field d and protected integer field e and private field f.
Write your answer to all three questions below:
Here is the completed code for this problem. Answers for each question is provided as comments in the code. Go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
using System;
//class A with needed attributes
class A{
private
int x;
protected
int y;
public
int z;
}
//class B with needed attributes
class B: A{
public
int d;
protected
int e;
private
int f;
//method to set all accessible variables to
2
public void
Foo(){
//from B class, we
can alter y and z attributes in super class and
//all attributes in
B class. x atribute cannot be altered because it is
//private in class
A
y=2;
z=2;
d=2;
e=2;
f=2;
}
//if we declare x,y,z variables as public,
it will show several warnings that
//this will hide the super class variables
x, y and z. i.e it is possible to
//declare values like below, but it will
hide super class variables. This warning
//will be shown to the variables y and z
only, since x is private. but there will
//be another warning that x's value is
never assigned or used as there is no way
//to access or alter the value of x as
there is no mutator or accessor method for x.
public
int x, y, z;
}
//class Program with Main()
public class Program
{
public static void
Main(string[] args){
//creating an
object of B
B
objB=new B();
//from outside the
B class, we can only access variables d and z since those two
//are the only
public variables. private and protected members cannot be
accessed
//outside the
class, so we can set variable d in B class and variable z in A
class to 1
objB.d=1;
objB.z=1;
//calling Foo
method on objB, now the variables y,z,d,e and f will have the value
2
objB.Foo();
}
}