Basic Class and Object in C# | My Assignment Tutor

12/04/20191Basic Class and Objectin C#Week 2Objects and ClassesThe objectives of this chapter are:To discuss important aspects of the softwaredevelopment processTo define objects and classesTo understand object models and class modelsTo explain instance variables and instance methodsTo explain constructors12/04/20192One of the primary features of the O-O paradigm is its ability tomanage complexity.Clear identification of system entities (objects)Abstract classification of system entities (classes)Clear delineation of entity boundaries (roles, responsibilities,encapsulation, cohesion, coupling)Clear separation of Abstraction boundaries (realistic class hierarchies)Less ambiguous mapping between the real world and the softwarecomponents modelling the real world. (objects)Unfortunately, the O-O paradigm is not clearly understoodMany programmers simply think that creating classes is OO programmingMany programmers erroneously think that because they use a languagewhich supports OO concepts they are implementing OO designsMany programmers, when confronted with code, cannot identify whether itis object-oriented and, if so, what elements make it OO.The Object Oriented ParadigmCreating ClassesObjects in the object model are formalizedObjects are abstracted into classesOnly attributes and methods relevant to our domain are classified.Attributes are formalized into instance variablesBehaviour is formalized into methodsClasses are represented on a class diagramObject interaction is also abstractedAssociations are identifiedAdded to class diagramClasses and the class diagram represent the static structure ofthe systemHow the system behaves is not represented by this model.12/04/20193Example Object ModelCreditDebitDebitDebitDebitCreditCreditCreditLedgerTransactionTransactionTransactionTransactionAccountAccountAccountExample Class ModelLedger-name:String+newAccount():boolean+closeAccount(): void+newTransaction(): voidAccount-number:int-owner:String-overdraftLimit:int-startDate:Date+findTransaction(): Transaction+close(): booleanTransaction-date: Date-amount: int+getDebitAccount(): Account+getCreditAccount(): AccountDebit Credit1 1..*1..*1 11..*12/04/20194Objects and ClassesProgrammers implement classesClasses are templates or blueprints for ObjectsData and methods are defined within ClassesClasses must provide an implementation such that objects created fromthose classes behave as those defined in the Object model.An Object is the manifestation of a classAn object is an Instance of a classThe process of creating an object is called instantiationThe attributes of an object are called instance variablesThe methods of an object are called instance methodsIn C#, Objects are created using the new keyword:Employee anEmployee = new Employee();Example Class Definitionpublic class Employee{String name;int salary;Date startingDate;[… more variable definitions …]public int getSalary(){return salary;}public int computeHourlyRate(){// calculate hourly rate from salary}[… more method definitions …]}InstanceVariables:Methods:12/04/20195EncapsulationEncapsulation is a very important O-O conceptEach object has 2 views. An internal view and an external viewEncapsulation is a form of protectionAlso called Information HidingThe outside world does not have direct access to the internalimplementation or representation of an objectAs long as the external view does not change, the internal view can takeon any form without affecting the outside worldBy hiding data and providing methods to gain access to it, an object canmaintain high data integrityMethods have the responsibility of maintaining data integrityprivate visibility offers full encapsulationprotected and default offer limited encapsulationpublic offers no encapsulationpublic class Account{private int number;private intoverdraftLimit;private Date startDate;private String owner;[… methods …]}Encapsulation ExampleClass Definition: Instances:number = 11346overdraftLimit = 1000startDateownerFred Jonesnumber = 12364overdraftLimit = 300startDateownerBillyWiggsInstance variables are encapsulated.– no direct access from outsidethe objectEach object has its own variables.These variables are declaredwithin the class.May 1,2001June 15,199412/04/20196Defining Instance MethodsMethod definitions include a method signature and a methodbody.Methods signatures are defined with the following syntax:The return type can be:a fundamental data typean object referencevoid (no return)Parameters are optionalIf the method takes no parameters, empty brackets are required ()Multiple parameters are separated by commasParameters are defined by type and nameA parameter is a local variable whose scope is the method.modifier return_type method_name(type name, …)Defining Instance Methods – VisibilityMethods have the same visibility modifiers as variablespublic – the method can be invoked from anywhereprivate – the method can only be invoked from within the classprotected – the method can be invoked directly from within the class,within the package, or from within any subclass.default (no modifier specified) – the method can be invoked directly fromwithin the packageIf a method is part of the class’s public interface (externalview), the method should be publicIf a method is part of the class’s internal implementation (ie,support method, etc), it should be private.Be careful using default or protected. Use only when justified.12/04/20197Defining Instance Methods – BodyA method’s body contains all the statements to be executedas part of the methodThe method body is contained within curly braces after themethod definition:Use {} placement and indentation to clearly show code structurepublic class CalculationSheet{public void performCalculations(){[… method body …]}public void clearSheet(){ }[…]}Returning values from methodsA method which has a non-void return type MUST return avalueThe return value’s type must match the type defined in the method’ssignature.A void method can use a return statement (with no return value) to exitthe method.The return value can be used the same as any other expression.public class Car{private int currentGear;private int currentRpms;public int calculateSpeed(){return currentRpms * currentGear;}}12/04/20198Classes as typesWhen a class is defined, the compiler regards the class as anew type.When a variable is declared, its type can be a primitive type or“Class” type.Any variable whose type is a class is an object reference.The variable is a reference to an instance of the specified class.The variables holds the address (in memory) of the x;0Employee anEmployee;nullNote: null means“refers to noobject”null Referencesnull means “refers to no object”Object references can be compared to null to see if an objectis present or not.null is the default value of an object reference before it isinitializedEmployee anEmployee;[…]if (anEmployee == null){ }12/04/20199Initializing Object References – newTo initialize an object reference, you must assign it theaddress of an objectThe new operator creates a new instance and returns theaddress of the newly created objectnew allocates memory for the objectnew also invokes a method on the object called a constructornew returns the address of the memory allocated for the object.Employee anEmployee;[…]anEmployee = new Employee();Assigning Object ReferencesAssigning one reference to another results in two referencesto the same objectIf two references contain the same memory address, they are referring tothe same object.Remember testing for equality of Strings using ==Each object has a reference countWhen an object’s reference count becomes zero, it will be collected bythe garbage collectorEmployee anEmployee = new Employee();Employee anotherEmployee = anEmployee;EmployeeanEmployeeanotherEmployee12/04/201910Invoking Instance MethodsTo invoke a method on an object, use the . (dot) operator• If there is a return value, it can be used as an expressionobjectReference.methodName(parameters);Car aCar = new Car();[…]if (aCar.calculateSpeed()>110){System.out.println(“You’re Speeding!”);}[…]Passing Parameters to MethodsMethod parameters are declared in the method’s signature.When a method invocation is made, any parameters includedin the invocation are passed to the methodAll parameters are passed by value. Ie, a copy is madeThe value of fundamental data types are copiedThe value of object references (ie memory addresses) are copied• Parameters become variables within the method. They arenot known outside the method.public float calculateInterestForMonth(float rate){return lowBalanceForMonth * (rate/12.0);}12/04/201911Overloading MethodsJava allows for method overloading.A Method is overloaded when the class provides severalimplementations of the same method, but with differentparametersThe methods have the same nameThe methods have differing numbers of parameters or different types ofparametersThe return type MUST be the samepublic float calculateInterestForMonth(){return lowBalanceForMonth * (defaultRate/12.0);}public float calculateInterestForMonth(float rate){return lowBalanceForMonth * (rate/12.0);}Accessor Methods – getsObjects have variables.Because of encapsulation, those variables are generally privateHowever, the outside world may need to use those variablesThe class implementor may choose to add a “get” method to return thevalueThe usual name of the get method is the name of the variableprefixed with the word “get”getName(), getAddress(), getPhone(), getBalance()public class BankAccount{private float balance;public float getBalance(){return balance;}12/04/201912Accessor Methods – setsSimilarly, the outside world may need to set the value of aninstance variableThe class implementor may choose to implement a set method.The responsibility of the set method is to set the appropriate variableWHILST MAINTAINING data integrity of the object.The usual name of the set method is the name of the variableprefixed with the word “set”setName(), setAddress(), setPhone(), setBalance()public class BankAccount{private String ownerName;public void setOwnerName(String aName){ownerName = aName;}Initializing Objects – ConstructorsWhen an object is created, all instance variables are initializedto the default value for their typeFundamentals are 0, 0.0, ‘00’ or falseObject references are nullIn order to put the object into a usable state, its instancevariables should be initialized to usable valuesThis could be accomplished by calling the various set methodsThis is not always possible because it is not required that all instancevariables have set methods.C# provides for another method of initializing objectsWhen an object is created, a constructor is invoked. Theresponsibility of the constructor method is to initialize theobject into a usable state.12/04/201913ConstructorsConstructors have the following characteristicsThere is NO return type. NOT even voidThe method name is the same name as the classConstructors can be overloadedIn order to put the object into a usable state, its instancevariables should be initialized to usable valuesThis could be accomplished by calling the various set methodsThis is not always possible because it is not required that all instancevariables have set methods.C# provides for another method of initializing objectsWhen an object is created (using new), a constructor isinvoked. The responsibility of the constructor method is toinitialize the object into a usable state.Constructors – Examplepublic class BankAccount{String ownersName;int accountNumber;float balance;public BankAccount(){ }public BankAccount(int anAccountNumber){accountNumber = anAccountNumber;}public BankAccount(int anAccountNumber, String aName){accountNumber = anAccountNumber;ownersName = aName;}[…]}12/04/201914Constructors – Examplepublic static void main(String[] args){BankAccount anAccount = new BankAccount();BankAccount anotherAccount = new BankAccount(12345);BankAccount myAccount = new BankAccount(33423, “Craig”);}When an object is created (using new) the compilerdetermines which constructor is to be invoked by theparameters passedMultiple constructors allows the class programmer to define manydifferent ways of creating an object.ConstructorsIf no constructors are defined for a class, the compilerautomatically generates a default, no argument constructorAll instance variables are initialized to default values.However, if any constructor is defined which takesparameters, the compiler will NOT generate the default, noargument constructorIf you still need one, you have to explicitly define one.12/04/201915Q & A sessionWhat is the difference between classes and objects?What are the modifiers for classes, instance variables andmethods? What do they mean?What is encapsulation? Why is it important?How are method parameters defined?How are method parameters passed?How do accessor methods support encapsulation?What are constructors?


Leave a Reply

Your email address will not be published. Required fields are marked *