Thursday, December 25, 2008

super & base keywords in Java and C#

Hi folks,

Nowadays i'm doing some programming in java,and since all of you know each of these languages are close to each other, I was implementing a class diagram i have done it on class designer in VS 2008.

I had the following inheritance case : a parent class called Publication and a dervied class called Book from publication.

I want in this post to highlight the difference to call the parent class from the derived class in java vs. C#,this is very useful for C# developers if they are reading any java code or vice versa.

If you try to implement the following: the derived class constructor is calling the parent class constructor the code in java and C# will be as follows:

// Java Code :

public class Publication
{
public Publication(String title)
{
this.title=title;
}
}
public class Book extends Publication
{
public Book(String title,String ISBN)
{
//super means the constructor of book will pass title to the publication constructor (Parent).
super(title);
this.ISBN=ISBN;
}
}


// C# Code :

public class Book
{
public Book(string title, string issueNo) : base(title)
{ // base means the title parameter will be passed to the parent class constructor.
this.issueNo = issueNo;
}
}

base and super keywords in c# and java are doing the same functionality by calling the parent class constructor in this case.

base and super used to refer to the parent class in general.


Hope this tip be useful.



Regards,
Mostafa arafa

No comments: