Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Inheritance and Polymorphism.
Inheritance Inheritance Reserved word protected Reserved word super
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Object-Oriented PHP (1)
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Introduction to Classes SWE 344 Internet Protocols & Client Server Programming.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Inheritance in the Java programming language J. W. Rider.
Encapsulation, Inheritance & Polymorphism. OOP Properties Encapsulation ­The process of creating programs so that information within a class is not accessible.
CIS 3301 C# Lesson 7 Introduction to Classes. CIS 3302 Objectives Implement Constructors. Know the difference between instance and static members. Understand.
Programming using C# for Teachers Introduction to Objects Reference Types Functions of Classes Attributes and Types to a class LECTURE 2.
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Introduction to Object-Oriented Programming Lesson 2.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Classes, Interfaces and Packages
Class Inheritance SWE 344 Internet Protocols & Client Server Programming.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 More About Derived Classes and Inheritance Chapter 9.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Inheritance and Polymorphism
Modern Programming Tools And Techniques-I
Creating Your Own Classes
Inheritance and Polymorphism
Corresponds with Chapter 7
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Lecture 22 Inheritance Richard Gesick.
Fundaments of Game Design
CIS 199 Final Review.
Final and Abstract Classes
Presentation transcript:

Section 5 – Classes

Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging data and behaviour into a single unit - the class Inheritance –Reuse of code through extending program units Polymorphism –Multiple implementations of the same behaviour

Classes in C# Classes model real-world objects and define – Attributes (state, properties, fields) – Behaviour (methods, operations) Classes describe the structure of objects – Objects describe particular instance of a class Properties hold information about the modeled object relevant to the problem Operations implement object behaviour

Classes Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces { }. using System; public class House {... } public class Program { public static void Main() { int bedrooms = 3; // assuming bedrooms defined in House }

Basic syntax for class declaration Class comprises a class header and class body. public class class_name { class body } Note: No semicolon (;) to terminate class block. But statements must be terminated with a semicolon ; Class body comprises class members – constructor, data fields and methods.

In C#, individual classes and class members need to be prefixed with visibility modifiers. By default, if you declare a member variable (or anything else) in a class but do not specify its access level, the member is considered private and cannot be accessed from outside, i.e. by a non-member of that class. Therefore, to make a member accessible by other classes, you must declare it as public. You can use a mix of public and private members in a class and there is no rule on which access level should be listed first or last.

C# - Basics: Classes Declaration public Class MyClass {...} Constructors public MyClass(parameters) {...} new operator – create an instance of the class MyClass objMyClass = new MyClass();

Variables of a class type are created with the new operator using System; public class House {... } public class Program { public static void Main() { House MyHouse = new House(); // create object }

Classes in C# can have members: – Data fields, methods, properties, indexers, events, operators, constructors, destructors, … – Inner classes Members can have access modifiers – public, private, … Members can be – static (common) or specific for a given object

Class Definition and Members Class definition consists of – Class declaration – Data Fields – Constructors – Properties – Methods

Contents of Classes class class_name {... data fields, constants methods constructors properties derived classes... }

Every class has a constructor, which is called automatically any time an instance of a class is created. The purpose of constructors is to initialize class members when the class is created. Constructors do not have return values and always have the same name as the class. Classes can have multiple constructors, as long as the parameter list is different for each constructor. The constructor with no parameters is known as the default constructor. If a class does not define any constructors, an implicit parameterless constructor is created.

Calling the constructor ClassName objectName = new ClassName(argumentList); Or ClassName objectName; objectName = new ClassName(argumentList);

public class Person { private string name; private int age; // Parameterless constructor public Person() { name = null; age = 0; } // Constructor with parameters public Person(string name, int age) { this.name = name; this.age = age; } // More code... } As rule constructors should initialize all class fields. 14

using System; class OutputClass { private string myString; // Constructor public OutputClass(string inputString) { myString = inputString; } public void printString() { Console.WriteLine(myString); } Continued …

// Program start class class ExampleClass { // Main begins program execution. public static void Main() { // Instance of OutputClass OutputClass outCl = new OutputClass("This is printed by the output class."); // Call OutputClass method outCl.printString(); }

To create an instance (i.e. object) of a class, use the new operator which invokes the class constructor. new class_name(parameters) Variables of type class_name can be created in this way: class_name object_name = new class_name(params); The dot operator (. ) is used in conjunction with the object to access the members (properties and methods) of a class (like C++ and Java).

Access Modifiers Class members can have access modifiers – Used to restrict the classes (i.e. clients) able to access them – Supports the OOP principle "encapsulation“ Class members can be: – public – accessible from any class – private – accessible from the class itself only There are others!

Accessor and Mutator Examples public double Get NoOfSquareMeters( ) { return noOfSquareMeters; } public void Set NoOfSquareMeters(double squareMeters) { noOfSquareMeters = squareMeters; } Accessor Mutator

Property A new feature for C# - another way of implementing accessor and mutator methods. Properties look like a data field – But more closely aligned to methods Standard naming convention in C# for properties – Use the same name as the instance variable or field, but start with uppercase character

The Role of Properties Expose object's data to the outside world Control how the data is manipulated – Ensure the internal object state is correct – E.g. price should always be kept positive Properties can be: – Read-only – Write-only – Read and write

Defining Properties Properties work as a pair of methods – Getter and setter Properties should have – Access modifier (public) – Return type – Unique name – Get and / or Set part – Can contain code processing data in specific way, e.g. apply validation

Defining Properties – Example public class Point { private int xCoord; private int yCoord; public int XCoord { get { return xCoord; } set { xCoord = value; } } public int YCoord { get { return yCoord; } set { yCoord = value; } } // More code... } 23

class MyClass { private string message ; public string Message { get { return message; } set { message = value; } class Program { static void Main() { // create instance of MyClass MyClass greetings = new MyClass(); greetings.Message = "Hello World!"; string answer = greetings.Message; Console.WriteLine("{0}", answer); Console.ReadLine(); }

Dynamic Properties Properties are not bound to a class field – they can be used calculate a value dynamically public class Rectangle { private double width; private double height; // More code... public double Area { get { return width * height; }

How to Use Classes 1.Create an instance – Initialize its fields 2.Manipulate the instance – Read / modify properties – Invoke methods

Example - Define Class for a Dog Define a simple class that represents information about a dog – The dog should have name and breed – If there is no name or breed assigned to the dog It should be named “Fido" Its breed should be “Mongrel" – It should be able to view and change the name and the breed of the dog – The dog should be able to bark

To define a simple class that represents information about a dog The dog should have name and breed → data fields – string type If there is no name and breed assigned to the dog It should be named “Fido" Its breed should be “Mongrel" → constructors It should be able to view and change the name and the breed of the dog → get and set methods The dog should be able to bark → method

public class Dog { private string name; private string breed; public Dog() // Constructors { name = “Fido"; breed = “Mongrel"; } public Dog(string dogName, string dogBreed) { name = dogName; breed = dogBreed; }

public string Name // get and set properties { get { return name; } set { name = value; } } public string Breed // get and set properties { get { return breed; } set { breed = value; } } public void Bark() { Console.WriteLine("{0} said: Woof!", name); }

Task is as follows: – Create 3 dogs – Put all dogs in an array – Iterate through the array elements and ask each dog to bark – Note: Use the Dog class from the previous example 31 Example

public class Doggies static void Main() { // Use the Dog constructor to set name and breed Dog firstDog = new Dog(); // default Dog secondDog = new Dog(“Fritz”, “German Shepherd”); Dog thirdDog = new Dog(“Tommy”, “Bulldog”); // Save the dogs in an array Dog[] dogs = new Dog[] {firstDog, secondDog, thirdDog }; // Ask each of the dogs to bark foreach(Dog dog in dogs) { dog.Bark(); }

Inheritance Enables you to – Create a general class and then define specialized classes that have access to the members of the general class Associated with an "is a" relationship – Specialized class “is a” form of the general class A derived (or child) class inherits from a base (or parent) class The derived class inherits all the attributes and behaviour of the base class. The derived class may implement also its own attributes and behavior. The derived class may override inherited attributes and behaviour

Inheritance hierarchy for Shapes.

Extending Classes Use a single colon –Between the derived class name and its base class name Inheritance works only in one direction –A child inherits from a parent public class ChildClass : ParentClass {... }

Child class may implement its own constructors, attributes and methods in addition to those inherited from the parent class. Instantiating an object of a derived class - Calls the constructor for both the base class and the derived class - The base class constructor will execute first Any derived class inherits all the data and methods of its base class - Including private data and methods - Cannot use or modify private data and methods directly

using System; public class ParentClass { public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("I'm a Parent Class."); } public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); } Child class object invokes print() inherited from parent class.

Creating Base Classes for Inheritance Can define your own classes from which other classes can inherit Base class is also called the super or parent class Data members are defined with a private access modifier Constructors are defined with public access modifiers Properties offer public access to data fields

Overriding Base Class Methods Derived class contains data and methods defined in the original class Polymorphism – Using the same method or property name to indicate different implementations Derived class can override and hide methods and data from the base class

public class Animal { public void Greet() { Console.WriteLine("Hello, I'm some sort of animal!"); } public class Dog : Animal { } This example defines an Animal class, with a simple method to output a greeting. Then a derived Dog class is defined - the Dog class inherits from the Animal class.

Animal myAnimal = new Animal(); myAnimal.Greet(); Dog myDog = new Dog(); myDog.Greet(); // use parent class method Even though we have not defined a Greet() method for the Dog class, it still knows how to greet us, because it inherits this method from the Animal class. May also define a Greet() method in the Dog class … that overrides the one in the parent class.

public class Animal { public virtual void Greet() { Console.WriteLine("Hello, I'm some sort of animal!"); } public class Dog : Animal { public override void Greet() { Console.WriteLine("Hello, I'm a dog!"); } Besides the added method on the Dog class, you should notice two things: I have added the virtual keyword to the method in the Animal class, and on the method in the Dog class, I use the override keyword. In C#, you are not allowed to override a member of a class unless it is marked as virtual.

If you want to, you can still access the inherited method, even when you override it, using the base keyword. public override void Greet() { base.Greet(); Console.WriteLine("Yes I am - a dog!"); } Inheritance is not only from one class to another - you can have a whole hierarchy of classes, which inherits from each other. - For instance, we could create a Puppy class, which inherits from our Dog class, which in turn inherits from the Animal class. What you cannot do in C#, is to let one class inherit from several other classes at the same time. - Multiple inheritance, as it is called, is not supported by C#.

Accessing Base Class Methods from a Derived Class Use the keyword base to access the parent class method

Overriding Methods Replace the method defined at a higher level Keyword override included in derived class – Base method includes virtual, abstract, or override keyword Overriding differs from overloading a method – Overridden methods have exactly the same signature – Overloaded methods each have a different signature

Overriding Methods (continued) Example of polymorphism – ToString( ) method can have many different definitions – ToString( ) uses the virtual modifier, implying that any class can override it Derived classes inherit from a base class – Also called subclasses or child classes Protected access modifiers – Access only to classes that derived from them – Access to change data in the base class