Thursday, September 19, 2024

C# Inheritance for Java Programmers

So what is a class? A class is a plan or a blueprint for an object, like a blueprint for a house. What if you want your house to look like a neighbor’s house? Well, you change the blueprint and add another fireplace.

When writing classes, we are actually writing blueprints for objects. Deriving from a class that we will call the parent_class to create a child_class is actually done for software reuse. Why write code over and over when you can reuse the code you have? Why do we need do derive or inherit from a class? So when we need to add functionality to that class that is not available in our base class, we derive the base class.

In Java we express this in the following way:

class child_class extends parent_class
{
//class extends
}

In C# the syntax is:

class child_class : parent_class
{
//class extends
}

An abstract class cannot be instantiated in Java, or in C#, in other words you cannot create an object of that class. An abstract class cannot be instantiated directly, and it is an error to use the new operator on an abstract class. While it is possible to have variables and values whose compile-time types are abstract, such variables and values will necessarily either be null or contain references to instances of non-abstract classes derived from the abstract types.

All Java classes are derived, directly or indirectly, from the Object class. As you can tell from the following program, inherited variables and methods can be used in the derived class as if they had been declared locally.

Using an Inherited Method
The subclass String inherits the method getClass() from the class Object. This is immaterial for a client of class String, as a client can directly invoke this method on objects of class String in the ordinary manner. If we have the following object references:

String stringRef = new String;
Object objectRef = new Object;

The next statement is valid:

System.out.println(stringRef.getClass());

Using a Method That Is Not Inherited
The child class String defines the method length(), which is not in the parent class Object, thereby extending the parent class. Invocation of this new method on an object of class String is shown here:

System.out.println( stringRef.lenth());

Changes you will need to make to a Java source to make it a C# source

using System; //ADDITION

//In a Java application you do not have to import anything
to run the
//same application. For the C#
//you have to add the “using System;”

class Words
{

//In Java, your main method is main; in C# if you the
compiler
// doesn’t find the Main
//method your application will not compile.

 public static void Main (String[] args)
 { // CHANGED FROM main to Main

 Dictionary webster = new Dictionary ();
 webster.page_message();
 webster.definition_message();
 } // method main
} // class Words

class Book
{
 protected int pages = 1500;
 public void page_message ()
 {
 Console.WriteLine (“Number of pages: ”
+ pages);

 } // method page_message
} // class Book

A Word on Visibility Modifiers
The visibility modifiers used to determine which variables and methods get inherited, and which do not. Variables that are declared public are inherited by the child class, and those declared private are not. Declaring variables public will violate the principles of encapsulation; therefore, Java provides a third visibility modifier protected. When a variable is declared protected, it retains some of the encapsulation properties and it is inherited by the derived class. The encapsulation with protected is not as tight as with private, but is better than if it were declared public.

The Super Reference
Constructors are an exception to the inheritance process in Java. They are not inherited by the derived class even though they have public visibility. In Java the super reference can be used to invoke the parent’s constructor. In C# there is no super keyword; it has been replaced by the keyword base.

In Java the constructor for the class is not inherited, but it can be invoked using the keyword super in C# is called using the keyword base.

To call the parent’s constructor in C# you only have to invoke base like this:

public child_class (int
inherited_parameter, int childs_parameter):
base (inherited_parameter)
{
// super (num_pages);
 this. childs_parameter = childs_parameter;

} // constructor Dictionary

The following is a simple C# application that illustrates a simple inheritance relationship[:

using System;
public abstract class Book
{
 protected int num_pages;
 public Book (int
num_pages)
 {
 this.num_pages = num_pages;
 } // constructor Book

 public void page_message ()
 {
  Console.WriteLine (“Number of pages: ”
+ num_pages);
 } // method page_message
} // class Book

class Dictionary : Book
{

 private int num_definitions;
//private int num_pages;

 public Dictionary (int
num_pages, int num_definitions): base
 (num_pages)
 {
  this.num_definitions = num_definitions;
 } // constructor Dictionary

 public void definition_message ()
 {
  Console.WriteLine (“Number of definitions:
” + num_definitions);
  Console.WriteLine (“Definitions per page:
” +
  num_definitions/num_pages);

  } // method definition_message
} // class Dictionary

class Words2
{
 public static void Main (String[] args)
 {
  Dictionary webster = new Dictionary (1500,
52500);
  webster.page_message();
  webster.definition_message();
 } // method main
} // class Words2

Accessing Parents Public and Private Members
The visibility modifiers determine if a variable or method is inherited by a child class. If a variable is inherited, then it can be referenced directly in the subclass by name as if it were declared locally in the subclass. From a child class you cannot access variables and methods that are private in the parent class. You can do that indirectly though, through a public method that calls a private method or variable.

Overriding
A child’s class can override (redefine) a parent’s definition of an inherited method. When a child class defines a method with the same name and signature as the parent class, we say that the child’s version overrides the parent’s version in favor of its own. In C#, to override the parent’s method you have to use the new keyword. The type of the object that is used determines which version of the method is called.

// CHILD CLASS
class message
{
 using System;

 class message
 {
  public static void Main (String[]
args)
  {
   parent parked = new parent();
   child dates = new child();
   parked.message();
   dates.message();

  } // method main
 } // class message
class parent
{
 public void message()
 {
  Console.WriteLine (“I am the father “);
  Console.WriteLine();

 } // method message
} // class parent

class child : parent
{
 new public void message()
 {
  Console.WriteLine (“I am the child “);
  Console.WriteLine();
 } // method message
} // class child

Polymorphism
The word polymorphism means “having many forms.” In Java, a reference that is declared to refer to an object of a particular class can be used to refer to an object of any class to which is related by inheritance. The ability for references of one class to refer to an object of another class is referred to as Polymorphism.

Upcasting
A subclass reference can be assigned to a superclass reference, because a subclass object can be used where a superclass object can be used. For example, the class Object is used to derive a class String, then a reference to Object can be used to refer to an object of the class String.

Object objectRef = new Object();

String stringRef = new String();

objectRef = stringRef;

Both references denote the same String object after the assignment. The reverse operation is also possible, but requires an explicit cast. Java is a strongly typed language, and if the objects are not related by inheritance you will get a compiler error. An inheritance relationship is also an is-a relationship. When a reference is used to invoke a method, the class of the object being referred to determine which method is invoked, not the type of the reference.

using System;

class Thought
{
 public void message()
 {
  Console.WriteLine (“Some people get lost in
thought ” +
  “because it’s unfamiliar territory.”);
  Console.WriteLine();

  } // method message
 } // class Thought

class Advice : Thought
{
 new public void message()
 {
  Console.WriteLine (“Avoid clichés like
the plague.”);
  Console.WriteLine();
 } // method message
} // class Advice

class message2
{
 public static void Main (String[] args)
 {

 Thought territory = new Thought();
 Advice cliche = new Advice();
 territory.message();
 cliche.message();
 territory = cliche;
 territory.message();
 } // method main
} // class Messages

All of this will compile just fine and will not give you runtime errors in C# or in Java (the Java version). The opposite, assigning a parent class reference to a child class reference, is also going to compile with no problems, but it will cause runtime errors in Java as well as C#.

Inheritance in C# allows only child-parent type relationships. As in Java, it does not allow multiple inheritance like in C++. However C# covers much more advanced issues in interfaces. Learning C# is easy for Java programmers. Most hardcore Java programmers will feel insulted learning C# (yet another Microsoft product), but you should look at it as a new interesting language, that’s easy to learn. Learning new technologies can offer more opportunities for employment.

Dragos Mincinoiu is a staff writer for Murdok.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles