CSC/ECE 517 Fall 2011/ch4 4a aj
Extending objects. : Consider one or more practical examples of Ruby's extend method--that is, examples that serve a real need and are not contrived. What facilities do other languages have for extending objects? Are they more or less powerful than Ruby's? Also consider prototype-based languages such as Self, which don't even provide classes.
Introduction
One of the most fundamental advantages of using Object Orientation is to reuse code. Rather than coding what was already coded, we can simply extend it to suit the needs of the new class. This helps to develop applications rapidly. Many languages provide built in libraries which can be included in classes. The O-O languages also provide a way to add functionality to existing classes through extension.
Implementation of Code Reuse:
“Inheritance” is the word used in O-O for the process of inheriting the members of a class and extending the functionality. A class can inherit from a single class or “Multiple Classes”, the latter is called as “Multiple Inheritance”. While a child class inherits from the parent class, it tends to inherit all the members of the class.
Comparison of Extend methods in Java, C# and Ruby.
In java:
A class declaration can use the extend keyword on another class as follows:
Class Course extends College { .............. }
When a class Child extends class Parent, Child automatically has all variables and methods defined in class Parent. If class Child defines a variable or method that has the same name in class Parent, class Child's definition overrides that of Parent's.
class Parent { int x; int y; int get(int a, int b){ x=a; y=b; return(0); } void Show(){ System.out.println(x); } } class Child extends Parent { public static void main(String args[]){ Parent p = new Parent(); p.get(5,6); p.Show(); } void display(){ System.out.println("Child"); } }
In C#:
Extension methods enable the programmer to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
class ExtensionMethod { static void Main() { int[] s = { 1, 55, 75, 93, 81, 96 }; var r = s.OrderBy(g => g); foreach (var a in result) { System.Console.Write(a + " "); } } }
Output: 1 55 15 81 93 96 The above example shows how to call the standard query operator OrderBy method on an array of integers.
In C++
Similar to Java, C++ also extends functionality of a base class to a derived class. The derived class can use the functions and variables of a base class as well as add their own functionality, thus making them a more specialized version of the base class. Similar to Java, overriding is also supported in C++. Here is an example of how a class is extended in C++.