2.2 MARCO CONCEPTUAL
2.2.11 EVALUACIÓN DE IMPACTO AMBIENTAL
As an example, I will start with a class that represents a person by a first and last name:
public class Person {
private string firstName;
private string lastName;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName; }
public string FirstName {
get { return firstName; }
}
public string LastName {
get { return lastName; } }
public override string ToString() {
return firstName + " " + lastName;
} }
The class is very simple and does not require many comments.
I will then define a class that represents an employee (in a company) when an employee is a person with two additional properties in the form of a title and a salary. The class Employee can be written in several ways, and you can for example think of it as an extension of the class Person with two new properties. The solution is not just to extend the Person class, as you can imagine this class is used in contexts in which concepts such as title and salary are not meaningful. Instead, you can write a class that inherits the Person class:
public class Employee : Person {
private string position; private int monthly;
public Employee(string firstName, string lastName, string position, int monthly) : base(firstName, lastName)
{
this.position = position; this.monthly = monthly; }
public string Position {
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language
103
Inheritance
get { return position; } }
public int Monthly {
get { return monthly; } }
public override string ToString() {
return base.ToString() + "\n" + position; }
}
First, notice after the name of the class Employee I have written
: Person
It is telling that Employee inherits Person. That Employee inherits Person means an Employee gets (inherits) all the properties that a Person has and expands with new properties. In this case extends an Employee a
Person with two new instance variables and associated properties. The Employee class has a constructor that initializes the two new instance variables, position and monthly, but it must also initialize the instance variables firstname and lastname in the base class. This requires that the constructor in Person is called, but when as a programmer you can’t call it directly, it is necessary to have a syntax that performs the constructor in the base class. It happens in the following:
Here, the colon and base() after constructor declaration means that the constructor in the Person is performed by firstName and lastName as the actual parameters. Specifically, what happens is when you create an Employee object the constructor in Person is performed, and then the constructor in Employee
is performed. When an Employee is specifically a Person, one can say that Person has to be created first, before the Employee can be created. An Employee object can then refer to the two properties FistName
and LastName. An Employee object can refer to FirstName, since it is a public property in Person and because Employee inherits Person. Employee objects can refer to all public members in both Person and
Employee. Private members can still only be referenced from within the class where they are defined. For example the variable firstname in Person can’t be referred from methods in Employee.
I will then define a class that represents a director. A Director is just a special kind of Employee, and the class can be defined as a class that inherits Employee:
public class Director : Employee {
public Director(string firstName, string lastName, int monthly) : base(firstName, lastName, "Director", monthly)
{ } }
The class is very simple and consists solely of a constructor, which transmit parameters to the constructor in the Employee class. All the other services as a director does occur (inherited) come from Employee
and Person.
At exactly the same way one can define a class that represents a bookkeeper:
public class Bookkeeper : Employee {
public Bookkeeper(string firstName, string lastName, int monthly) : base(firstName, lastName, "Bookkeeper", monthly)
{ } }
Now consider the following method:
static void Print(Employee e) {
Console.WriteLine(e);
Console.WriteLine("Monthly: {0}", e.Monthly);
Console.WriteLine("{0}, {1}", e.LastName, e.FirstName); }
The first statement prints the result of ToString() from the class Employee. The next one is not much mystery in, but you should note the last, which uses two properties, both of which are defined in Person. The parameter e has the type Employee, and you can thus especially use what is defined public in Person.
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language
105
Inheritance Consider also the following method, which creates two objects, respectively of the types Director and
Bookkeeper:
static void Test1() {
Director d = new Director("Olga", "Jensen", 8000); Bookkeeper b = new Bookkeeper("Karlo", "Hansen", 5000); Print(d);
Print(b); }
You should particularly note that the method calls Print() with the two objects d and b as actual parameters. It makes sense for d have the type Director, which specifically is an Employee.
Above, there are defined four classes that are linked in a hierarchy, as you can illustrate in the following way:
Person
Employee
Bookkeeper Director
When a class inherits another class, the class you inherit from is called the base class and the inheriting class is called a derived class. For example is Person the base class for Employee while Employee derives from Person. Sometimes Person instead of is called a super class, while the Employee is called a subclass. We say also that Person is a generalization of Employee and that Employee is a specialization of Person. This saying better reflected the relationship between Employee, Director and Bookkeeper in which Employee is a generalization of the Director and Bookkeeper and Director are specializations of Employee. Sometimes we talk also about the class that inherits as an extension of the base class corresponding to Employee
extends Person with new properties.
I will write another class, representing a consultant that is an Employee whose salary is calculated as a fixed monthly salary and a commission on the sale:
public class Consultant : Employee {
private double commission; private double sale;
public Consultant(string firstName, string lastName, int monthly,
double commission) : base(firstName, lastName, "Consultant", monthly)
{
this.commission = commission; }
public double Commission {
get { return commission; } }
public double Sale {
get { return sale; } set { sale = value; } }
public override int Monthly {
get { return monthly + (int)(sale * commission / 100); } }
}
Note first that a Consultant extends the class Employee with two new variables. One is initialized in the constructor, whereas the other gets a value by means of a property. There is not much to say. But if you look at the property Monthly, you should note two things: the word override, and that it refers to the variable monthly in the base class Employee – which is not possible because it is private. The problem is solved by changing the class Employee and instead defines the variable monthly as protected:
public class Employee : Person {
protected int monthly;
www.sylvania.com
We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of possibilities: Innovative technologies and new markets provide both opportunities and challenges. An environment in which your expertise is in high demand. Enjoy the supportive working atmosphere within our global group and benefit from international career paths. Implement sustainable ideas in close cooperation with other specialists and contribute to influencing our future. Come and join us in reinventing light every day.
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language
107
Inheritance If a member of a class is protected, it can be referenced by derived classes, as it was public while it from objects of this class looks as private. protected is a visibility between private and public, which allows derived classes to refer to members in the base class, while the base class maintains protection against other classes. Stated differently, then variable monthly may be referenced by subclasses of Employee, but not from classes that do not inherit Employee. A class should not make all of its variables protected, but only those variables that one must expect that the derived classes need to refer to. When you make a member protected you also are opening up the protection in relation to derived classes.
In this case, protected is only included to explain the concept, the problem could be solved in another way:
public override int Monthly {
get { return base.Monthly + (int)(sale * commission / 100); } }
where you with base refers to the property Monthly, which is defined in the base class.
There is now a definition of the property Monthly in both Employee and Consultant, and the meaning is that in Consultant shall override the property in Employee – give it a different meaning. For that to be possible, you must in Employee open up for it by declaring the property virtual:
public virtual int Monthly {
get { return monthly; } }
When that is the case, a derived class – here Consultant – can choose to override the property by entering the keyword override. If you do not, you get a warning that it hides the base class version.
It was the class Consultant, and below is shown a method that uses the class:
static void Test2() {
Consultant c = new Consultant("Gudrun", "Madsen", 2000, 10); c.Sale = 30000;
Print(c); }
It is not entirely obvious. Note that the property that is executed for Monthly, is the one in the class
Consultant, even though the parameter to the Print() method is of the type Employee. This means that the system “remembers” the type of the current object, even if the object in Print() is known as an Employee. It is an extremely important option known as polymorphism.
When you write a class, you have no guarantee that there not in the future is one that inherits the class and extends it with new features – and that is exactly also the idea of inheritance. However, there may be situations where you do not want this option and you can then declare the class sealed, meaning that it can’t be inherited. If for example you do not want it to be possible to inherit the class Director, you can define it as follows:
public sealed class Director : Employee {
public Director(string firstName, string lastName, int monthly) : base(firstName, lastName, "Director", monthly)
{ } }
Comment
Inheritance is not an especially difficult concept – at least not when you’ve seen it a few times – but there are certain things one must be aware of:
• A class – for example Employee – may have one or more derived classes, but a class can inherit only one class.
• Polymorphism – that the runtime system remembers the specific type of an object (the type which is used when the new object is created – is one of the most important concepts of object oriented programming.
Moreover, there are some names associated with inheritance, that it is important to understand:
• base
• protected
• virtual
• override
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language
109
The class Object
12 The class Object
I have above seen on some classes such as Coin, Dice, Cup etc. and these classes have not used inheritance – apparently, but actually, they have indirectly inherits a class called Object. If you do not write anything, then any class automatically inherit this class, and thus all classes without exception, directly or indirectly inherit Object. It is actually more than that, for any type whether it is a value type or reference type inherits Object.
C# defines an alias object of class System.Object, which is a reserved word, exactly the same way as the
string is an alias for the class System.String.
The class Object does not contain much, and its primary purpose is to be a common base class for all types. The class defines a few methods that I will mention below. First I will mention ToString() which returns the value of an object as a string. Consider the following class:
class ZipCode {
private string code; private string name;
EADS unites a leading aircraft manufacturer, the world’s largest
helicopter supplier, a global leader in space programmes and a worldwide leader in global security solutions and systems to form Europe’s largest defence and aerospace group. More than 140,000 people work at Airbus, Astrium, Cassidian and Eurocopter,
in 90 locations globally, to deliver some of the industry’s most exciting projects.
An EADS internship offers the chance to use your theoretical
knowledge and apply it first-hand to real situations and assignments during your studies. Given a high level of responsibility, plenty of
learning and development opportunities, and all the support you need, you will tackle interesting challenges on state-of-the-art products.
We welcome more than 5,000 interns every year across disciplines ranging from engineering, IT, procurement and finance, to strategy, customer support, marketing and sales. Positions are available in France, Germany, Spain and the UK.
To find out more and apply, visit www.jobs.eads.com. You can also
find out more on our EADS Careers Facebook page.
Internship opportunities
public ZipCode(string code, string name) {
this.code = code; this.name = name; }
public string Code {
get { return code; } }
public string Name {
get { return name; } }
}
When not specified otherwise, the class ZipCode inherits the class Object. Consider the following method:
static void Test1() {
ZipCode z = new ZipCode("7800", "Skive"); Console.WriteLine(z);
}
which created an object of type ZipCode, and this object is printed on the screen. Note that when the object is printed with WriteLine (), then it is the result of the object’s ToString() method that is printed. In this case there is no ToString() method in class ZipCode, but the program can be translated and run, and the result is the following:
The ToString() method that is carried out, comes from the class Object, and print the full name of the object’s type, here is the class’s namespace and class name. One can thus state that all objects without exception has a ToString() method, but it is the one who writes the object’s class, which is responsible for override the method so that it returns a meaningful result. As a class always inherits Object, that is why I’ve written override in all the classes that have defined a ToString() method – ToString() is a virtual
method in the class Object.
Object also defines a method called Equals() that have an object as a parameter. It is a method that returns true if the current object and the parameter are the same. If you execute the following method
static void Test2() {
ZipCode z1 = new ZipCode("7800", "Skive"); ZipCode z2 = new ZipCode("7800", "Skive"); Console.WriteLine(z1.Equals(z2));
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language
111
The class Object it will write False on the screen, and it was not what one would expect. The two objects z1 and z2 have the same value, but they are two different objects, each of which refers to their own object on the heap. The method Equals() as defined in the class Object, compares the object references, and as z1 and z2
are two different objects will Equals() returns false, even if the two objects have the same value. Should it be otherwise, it is up to the programmer to override the method Equals(), so it compares the values rather than references. If you want to override Equals() in the class ZipCode you can do the following:
public override bool Equals(object obj) {
if (obj is ZipCode) {
ZipCode z = (ZipCode)obj;
return code.Equals(z.code) && name.Equals(z.name); }
return false; }
Note first the is operator that may be used to test whether an object has a particular type. For Equals()
should return true, obj must be at least of the type ZipCode. If so, you can type cast it to a ZipCode. Then
obj is equal to the current object if both the zip code and the city name are the same. Note that this test is in fact based on that the string class overrides Equals() with value semantic.
I will mention another method in the class Object called GetHashCode(). It is a method of an object that returns an integer that can be perceived as an identification of the object. In general, this code is determined from the reference to the object, but it is in the same manner as for ToString(), and Equals() up to the programmer to override the method, if it has to return a code determined from the value of the object. There are different guidelines for how this code is to be determined, but you can observe that it is not a requirement that two different objects return different hash codes. However, it should be the case that if you have two objects obj1
and obj2 and obj1.Equals(obj2) is true, then must obj1.GetHashCode() be equal to obj2.GetHashCode(). I will not at this point to give examples of applying this method, but the examples will come later. Another reason to mention GetHashCode() on this point is that if you overrides Equals() without having to override GetHash- Code(), you get a warning from the compiler. In most cases, this warning could be ignored.
Consider the following method, where you should be especially noted that the method has an object as a parameter:
static void Print(object obj) {
Console.WriteLine(obj.GetType()); Console.WriteLine(obj.GetHashCode()); Console.WriteLine(obj);
You should also note the method GetType(), which is also a method in the class Object, which in this case is used to print the name of the object’s type. The following method creates an array of the type
object and prints its elements on the screen:
static void Test3() {
object[] t = { 23, 3.14, "Volmer", new Postnummer("7800", "Skive") }; for (int i = 0; i < t.Length; ++i) Print(t[i]);
}
If you run the method you get the following result:
You should primarily note two things:
• a method that as a formal parameter has an object may have an actual parameter of any type
• an array which type is object may contain anything irrespective of the type
At first glance it sounds smart, but you should be aware that this means that the compiler can’t type check, and thus a code based on the type object can very easily contain errors.
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language