Implementing Interfaces in Java and C


Implementing Interfaces in Java and C#

Now that our classes are defined, we need to actually implement them. We need to indicate in the class declaration that we intend to implement the interface, and we also need to write the methods that are contained in the interface.

In Java, we write the following to modify the Student class:

 /////// Student.java 
package Registration;
public class Student extends Person implements HTMLSource {
protected int GraduationYear;
public Student() {
GraduationYear = 0;
}
public void Modify( String First, String Last, int Graduation )
{
super.Modify( First, Last );
GraduationYear = Graduation;
}
public void Display()
{
super.Display();
System.out.print( " " + GraduationYear );
}
public String GetHTML()
{
String Ret = new String();
Ret = " < B > "+FirstName+" & nbsp;"+
LastName+" < /B >& nbsp;Graduates in "+
GraduationYear;
return( Ret );
}
}

Note how the first line of Student has been modified to use the syntax implements HTMLSource , which means we will be implementing that behavior. The next step is to add the GetHTML method to the class (listed in the preceding code in bold font).

Taking the same approach for C#, we write the following:

 /////// Student.cs 
using System;
namespace Registration
{
public class Student : Person, IHTMLSource
{
protected int GraduationYear;
public Student() {
GraduationYear = 0;
}
public void Modify( String First, String Last, int
Graduation ) {
base.Modify( First, Last );
GraduationYear = Graduation;
}
new public void Display() {
base.Display();
System.Console.Out.Write( " " + GraduationYear );
}
public string GetHTML() {
return " < B > " + FirstStr + " & nbsp;"+ LastStr +
" < /B >& nbspGraduates in " +
GraduationYear;
}
}
}

In this C# example, note that the syntax for declaring that you are implementing an interface only requires you to list the interface name after the class name is declared. In the preceding code, we state that we are deriving from Person and are implementing IHTMLSource , because Person is a class and IHTMLSource is an interface.




OOP Demystified
OOP Demystified
ISBN: 0072253630
EAN: 2147483647
Year: 2006
Pages: 130

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net