ThucHanh2 Interface
ThucHanh2 Interface
Solution:
1
Figure 2.4: Output of Vehicle.cs
2. Consider the previous question. Override the Run() method in the derived class to display a
message “The CAR is running”.
Solution:
3. Write a program to display the value of two integers using parameterized constructor and a
method. Create two objects of this and pass the sets of values (10, 20) and (30, 40)
2
respectively. Overload the ‘+’ operator to add the two x values and two y values of these
objects to form a new object (x, y). The answer should be (10+30, 20+40) = (40, 60).
Solution:
4. Write a program to demonstrate the use of abstract class. Create two derived classes Blue
and Green based on a generic Color class. Color class should define a template for a
method Fill(string colorname). This method should be implemented by the classes
Blue and Green. The Fill method should display a message “Fill me up with” and then
the color name.
Solution:
3
using System;
class ColorDemo
{
static void Main()
{
Blue b = new Blue();
b.Fill("Blue");
5. Write a program to demonstrate polymorphism and the use of keyword base. Declare a class
AppWindow having a virtual method CreateWindow(), displaying message “Window:
drawing Window at top, left” where top and left are integer variables initialized in the
constructor. Derive a class ListBox from AppWindow and initialize three parameters in its
constructor; top, left and a string variable listBoxContents. Override
CreateWindow() with the message “Writing string to the listbox: listBoxContents”
4
and also display the virtual method of the base class. Derive another class Button from
AppWindow and override the virtual method CreateWindow() with the message
“Drawing a button at top, left”.
Solution:
using System;
}
// ListBox derives from AppWindow
public class ListBox : AppWindow
{
private string listBoxContents;
// Overriding CreateWindow
public override void CreateWindow()
{
base.CreateWindow(); // invoking base method
Console.WriteLine ("Writing string to the listbox: {0}",
listBoxContents);
5
}
}
// Button derives from AppWindow
public class Button : AppWindow
{
public Button(int top, int left): base(top, left)
{
}
// Overriding CreateWindow
public override void CreateWindow( )
{
Console.WriteLine("Drawing a button at {0}, {1}\n", top,
left);
}
}
public class Tester
{
public static void Main()
{
AppWindow win = new AppWindow(-110,-0);
win.CreateWindow( );
win = new ListBox(3,4,"This is a list box");
win.CreateWindow();
win = new Button(5,6);
win.CreateWindow();
}
}