The document discusses classes and objects in object-oriented programming. It explains that a class describes the characteristics and capabilities of an entity, while objects are instances of a class that are created in memory at runtime. It provides examples of a Dog class and objects for specific dogs. The document also covers topics like class declarations, access modifiers, constructors, static members, and properties.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
74 views37 pages
Classes and Objects: Prof. M Nataraja Suresh
The document discusses classes and objects in object-oriented programming. It explains that a class describes the characteristics and capabilities of an entity, while objects are instances of a class that are created in memory at runtime. It provides examples of a Dog class and objects for specific dogs. The document also covers topics like class declarations, access modifiers, constructors, static members, and properties.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37
Classes and Objects
Prof. M Nataraja Suresh
Classes and Objects • Instances of a class are called objects. Objects are created in memory when your program executes. • A Dog class describes what dogs are like: they have weight, height, eye color, hair color, disposition, and so forth. They also have actions they can take, such as eat, walk, bark, and sleep. • A particular dog (such as my childhood dog Tommy) has a specific weight (62 pounds), height (22 inches), eye color (black), hair color (brown), disposition (masculine), and so forth. He is capable of all the actions of any dog • classes in object-oriented programming encapsulate the characteristics and capabilities of an entity in a single, self-contained and self-sustaining unit of code. Class Declaration [attributes] [access-modifiers] class identifier [:base-class] {class-body}
public class Tester
{ public static int Main( ) { ... } } Inside a Class • When you declare a new class, you define the properties of all objects of that class, as well as their behaviors • In windowing environment, we create screen widgets(commonly known as controls), like ListBox in Windows programming • List boxes have a variety of characteristics -- for example, height, width, location, and text color. Programmers have also come to expect certain behaviors of list boxes: they can be opened, closed, sorted, and so on. • We can create a new type, ListBox, which encapsulates these characteristics and capabilities. Such a class might have member variables named height, width, location, and text_color, and member methods named sort( ), add( ),remove( ) • we create an object of that type ListBox myListBox; using System; public class Time Simple Time Class { // public methods public class Tester public void DisplayCurrentTime( ) { { Console.WriteLine( static void Main( ) "stub for DisplayCurrentTime"); { } Time t = new Time( ); // private variables int Year; t.DisplayCurrentTime( ); int Month; } int Date; } int Hour; int Minute; int Second; } Access Modifiers • An access modifier determines which class methods can see and use a member variable or method within a class • private is the default accessibility level, you do not need to make it explicit How protected internal works? • This example contains two files, Assembly1.cs and Assembly2.cs. • The first file contains a public base class, BaseClass, and another class, TestAccess. • BaseClass owns a protected internal member, myValue, which is accessed by the TestAccess type. • In the second file, an attempt to access myValue through an instance of BaseClass will produce an error, while an access to this member through an instance of a derived class, DerivedClass will succeed. Method Arguments • Methods can take any number of parameters.1 The parameter list follows the method name and is encased in parentheses, with each parameter preceded by its type void MyMethod (int firstParam, button secondParam) { // ... } Creating Objects • The primitive C# types (int, char, etc.) are value types, and are created on the stack. • Objects, however, are reference types, and are created on the heap, using the keyword new, as in the following: Time t = new Time( ); • t does not actually contain the value for the Time object; it contains the address of that (unnamed) object that is created on the heap. t itself is just a reference to that object. Constructors • whenever we instantiate an object, say Time t = new Time( ); a constructor method is called • constructor, must either be defined by us (as part of your class definition) or let the Common Language Runtime (CLR) provide one on your behalf. • The job of a constructor is to create the object specified by a class and to put it into a valid state. • Before the constructor runs, the object is undifferentiated memory; after the constructor completes, the memory holds a valid instance of the class type. Constructors cont… • The default constructor creates the object but takes no other action. • Member variables are initialized to innocuous values (integers to 0, strings to the empty string, etc.) Constructors cont… • To define a constructor, declare a method whose name is the same as the class in which it is declared. • Constructors have no return type and are typically declared public. If there are arguments to pass, define an argument list just as you would for any other method
Initializers • It is possible to initialize the values of member variables in an initializer, instead of having to do so in every constructor. • Create an initializer by assigning an initial value to a class member: private int Second = 30; // initializer Copy Constructors • A copy constructor creates a new object by copying variables from an existing object of the same type. • C# does not provide a copy constructor, so if you want write one yourself. this - Keyword • The keyword this refers to the current instance of an object. The this reference is a hidden pointer to every nonstatic method of a class • It is used (1) to qualify instance members otherwise hidden by parameters (resolves ambiguity)
• to pass the current object as a parameter to another method
Static Members - Usage • The properties and methods of a class can be either instance members or static members. • Instance members are associated with instances of a type, while static members are considered to be part of the class. • You access a static member through the name of the class in which it is declared. • Say Button class has a static method SomeMethod( ). we invoke using Button.SomeMethod( ); rather than writing: btnUpdate.SomeMethod( ); • In C# it is not legal to access a static method or member variable through an instance Using Static Constructors • static constructor will run before any instance of your class is created • no access modifier (e.g., public) before the static constructor • static member methods cannot access nonstatic member variables, and so Name must be declared a static member variable Using Private Constructors • In C# there are no global methods or constants. • You might find yourself creating small utility classes that exist only to hold static members. • You can prevent any instances from being created by creating a default constructor (one with no parameters), which does nothing, and which is marked private. • With no public constructors, it will not be possible to create an instance of your class Using Static Fields – For Instance Counting Destroying Objects • C# provides garbage collection, you never need to explicitly destroy your objects. • However, if your object controls unmanaged resources, you will need to explicitly free those resources when you are done with them. • Implicit control over unmanaged resources is provided by a destructor, which will be called by the garbage collector when your object is destroyed. • Managed objects are created, managed and under scope of CLR, pure .NET code managed by runtime, Anything that lies within .NET scope and under .NET framework classes such as string, int, bool variables are referred to as managed code. • UnManaged objects are created outside the control of .NET libraries and are not managed by CLR, example of such unmanaged code is COM objects, file streams, connection objects, Interop objects. (Basically, third party libraries that are referred in .NET code.) C# destructor • C#'s destructor looks, syntactically, much like a C++ destructor, but it behaves quite differently Destructors Vs Dispose • If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the Idisposable interface. • The IDisposable interface requires its implementers to define one method, named Dispose( ), to perform whatever cleanup you consider to be crucial. • The availability of Dispose( ) is a way for your clients to say "don't wait for the destructor to be called, do it right now.“ • If you provide a Dispose( ) method, you should stop the garbage collector from calling your object's destructor. • To do so, call the static method GC.SuppressFinalize( ), passing in the this pointer for your object. Using statement for Earliest Disposal • we cannot be certain that your user will call Dispose( ) reliably, and because finalization is nondeterministic (i.e., you can't control when the GC will run) • C# provides a using statement that ensures that Dispose( ) will be called at the earliest possible time. • The idiom is to declare that objects you are using and then to create a scope for these objects with curly braces. When the close brace is reached, the Dispose( ) method will be called on the object automatically • The using statement also protects you against unanticipated exceptions. No matter how control leaves the using statement, Dispose( ) is called. It is as if there were an implicit try-catch-finally block. In-Out-Ref parameters example In-Out-Ref parameters example Overloading Methods • Two methods differ in their signatures if they have different names or different parameter lists. • Parameter lists can differ by having different numbers or types of parameters. Overloading Methods Encapsulating Data with Properties • The class designer wants to hide the internal state of his class in class members, and provide indirect access through a method • Properties allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method Encapsulating Data with Properties Readonly fields • We'd like to mark the static values as constant, but that is not possible because we don’t initialize them until the static constructor is executed. • C# provides the keyword readonly for exactly this purpose. Readonly fields