You are on page 1of 40

Lab Excercise C Sharp Programs : By PTSM

A class that represents a Point on the co-ordinate system.

p (x, y)
15
10
X
(0,0)

Y
Setter begin with Set<variableName>(parameters) – SetRollno(..), SetName(..)
Getter begin with Get<variableName>() – GetRollno(), GetName()
A boolean Getter begin with Is<variableName>() – IsFull(), IsOpened(), IsAlive()

class Point {
Fields are used to store
//data - variables data.
Attributes
private int x;
private int y; Methods are used to
perform operations on
//code – methods
Setters data.
public void SetX (int xx) {
x = xx;
} Class defines fields and ,
public void SetY (int yy){ methods.
y = yy;
} Encapsulation: putting
data and code together-
Getters binding of behavior and
public int GetX (){
return x; state to a particular
} object.
public int GetY (){
return y; Abstraction: providing
} essential and relevant
features and ignoring the
}
rest.

1 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

NULL
class TestPoint { OBJECT
p
x
static void Main () { 150 y
p
Point p; //object reference variable 150
p = new Point (); //creating an object and assigning an address to a variable

// or – above 2 lines can be combined into 1 line


// Point p = new Point();

// calling object’s setters – write operation SetY


p.SetX (15);
p.SetY (10);
GetY
x 15
// calling object’s getters – read operation
int x, y; y 10
SetX
x = p.GetX ();
y = p.GetY ();
Console.WriteLine(“ x = “ + x); GetX
Console.WriteLine(“y = “ + y);
}
p
} p.x = 10; // direct access

From outside CLASS


state

DATA (variables)

behavior

CODE (methods)

From outside

DATA hidden and all operations to data are performed though METHODS of the object.

2 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Class:
Definition: A class is a blue print that defines the variables and methods common to all objects
of a certain kind. This allows you to create objects.
Object:
Definition: An object is a software bundle of variables and related methods.

Object Life Cycle

As we work with objects in OOP, understanding


how objects are born,
live their lives,
and die is important.

Point p;
p = new Point();

1. Declaration:
Variable p will be used to refer to a Point object. Notice that a class name is used as
the variable's type.

2. Instantiation:
new is a C Sharp operator that creates the new object (allocates space for it).
An object is an instance of a class.

3. Initialization:
Point() is a call to Point's constructor, which initializes the object.

Using Object
Once you've created an object, you probably want to use it for something.
You may need information from it,
want to change its state, or have to perform some action.

Destroying an object
When it's time for the object to die, the object is removed from memory and .NET drops
its internal reference to it. You don't have to destroy objects yourself. A special part of
the .NET runtime called the garbage collector (GC) takes care of destroying all objects
when they are no longer in use.

3 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

RTC Bus Station


A B C

C2
BUS
PERSON
C1

E F
D

G H I
C3

CAR

Classes : C1, C2 and C3

Objects: A, B, C, D, E, F, G, H and I

4 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Input from keyboard

class TestPoint 2 {

static void Main () {


Point p = new Point();

Input

int x, y;
Console.WriteLine(“Enter value for X”);
x = int.Parse( Console.ReadLine());
Console.WriteLine(“Enter value for Y”);
y = int.Parse( Console.ReadLine());

p.SetX(x);
p.SetY(y);

x = p.GetX();
y = p.GetY();
//Console.WriteLine(“ x = “ + x + “, y= ” + y);
Console.WriteLine(“x={0}, y={1}”,x, y); OR

//Console.WriteLine(“x = “ + p.GetX() + “, y= “ + p.GetY());


}
}

Assigning object reference variable : Do not creates a copy of the object, you are only making a
copy of reference.

p1 150 x
Point p1,p2;
p1 = new Point(); y
p2 150
p2 = p1; 150

5 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

UML (Unified Modeling Language)

Class Diagram:

The UML class diagram is a graphical notation used to construct and


visualize object oriented systems.

A UML class diagrams made of:

A set of classes and


A set of relationships between classes.

Classes:

A consists of three parts

1. Class name
2. Class attributes(fields)
3. Class operations(methods)

Class Name

Class Attributes

Class Operations

Note: Name should be center aligned; Attributes and Operations should be left aligned.

6 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Class Name:

1. The name of the class

Class Attributes:

1. The name of the each attribute


2. The attribute type is shown after the colon (attribute name : attribute type)
3. Attributes map onto the member variables (data members) in the code

Class Operations:

1. The name of the each operation. It is a service the class provides


2. The type of method parameters are shown after the colon following the
parameter name
3. The return type of a method is shown after the colon at the end of the method
signature (operation name : return type)
4. Operations map onto the class methods in code.

Visibility and Access for attributes and operations of a class

The +, -, # and ~ symbols before an attribute and operation name in a class denote the
visibility of the attributes and operations.

+ denotes public attribute or operation


- denotes private attribute or operation
# denotes protected attribute or operation
~ denotes namespace/package attribute or operations

7 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

The UML specifies two types of scope for attributes and operations

1. Instance
2. Classifier

Instance:
1. In case of instance members, the scope is specific to instance.

Classifier:
1. The scope is class.
2. Classifier members are commonly recognized as “static” in
many programming languages.
3. To indicate that a member has the classifier scope, its name
must be underlined. Otherwise as default, the instance scope
is considered.

Operation (method) parameter directionality

Each parameter in an operation may be denoted as in, out or inout which specifies its
direction with respect to caller.

In: states that parameter “p” passed to operation “op” by the caller. Here “p”
is the “in” parameter.

Out: states that parameter “p” is not set by the caller but is modified by
operation "op” and is passed back out. Here “p” called as “out”
parameter.

InOut: states that parameter “p” is passed to operation “op” by the caller and is
then possibly modified by “op” and is passed back out. “p” is the “inout”
parameter.

Default Values

The UML specification allows for the identification of default values in the attribute list
section by using the following notation.

attribute name : attribute type = default value

8 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Example:

ConsoleApp

Point TestPoint

- x : int
- y : int

+ SetX(x : int) : void + Main() : void


+ GetX() : int
+ SetY(y : int) : void
+ GetY() : int

9 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Variables
Instance variables
Class variables
Local variables
Block Level variables and Formal Arguments

class Variables {
private int v1; //instance
private static int v2; //class

public void method(int v3 //formal argument) {


int v4; //local

If(condition) {
int v5; //block level
}
}
}

Characteristics of instance variables and methods


The values for instance variables are provided by each instance of the class.
Instance of the same class share the same instance methods.
To use members, object reference is required.

Characteristics of class variables and methods


All instances of a class shared its class variables and methods
It is not necessary to have objects of a class to use its variables and methods.

Default Values
The constructors provide a default value for each member variable.
For value types: integer-0, floating point-0.0, Boolean-false, character-‘\u0000’
For reference types: null (neither zero nor blank)
Note: for local and block level variables; an explicit initialization is required

Assignment:
1. Course : description, fee and duration
2. Time: hours, minutes and seconds

10 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Understanding this keyword

class Point { class Point { class Point {

private int x; priv ate int x; priv ate int x;


priv ate int y; priv ate int y;
private int y;

public v oid SetX (int xx) { public v oid SetX (int x) {


public void SetX (int xx) { this.x = xx; this.x = x;
x = xx; } // x=x;
} public v oid SetY (int y y ) { }
public void SetY (int yy){ this.y = yy; public v oid SetY (int y ) {
} this.y = y;
y = yy;
// y=y;
}
}
public int GetX () {
return this.x;
public int GetX (){ } public int GetX () {
return x; public int GetY () { return x;
} return this.y; }
} public int GetY () {
public int GetY (){
return y;
return y;
}
}
}

} }

Within an instance method or a constructor, this is a reference to the current object - the object
whose method or constructor is being called. You can refer to any member of the current object from
within an instance method or a constructor by using this.

“this” with fields


The most common reason for using the this keyword is because a field is shadowed by a
method or constructor parameter.

“this” with constructors


From within a constructor, you can also use the this keyword to call another constructor
in the same class. Doing so is called an explicit constructor invocation.

“this” used as a method return type


Sometimes a method may want to return current object.

11 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class Point {
private int x; Point p1, p2;
private int y;

//1st object
public void SetX(int x) {
p1 = new Point();
this.x = x;
//x = x;
} //2nd object
p2 = new Point();
public int GetX() {
return x;
} p1.SetX(10); //1st

… p2.SetX(20); //2nd
}

X X

Y Y

STACK
p1-150 p2-250

this = 250
2nd call
x = 20 P2.SetX(20); //2nd
t

this = 150
1st call
p1.SetX(10); //1st
x = 10

12 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Points to remember

1. When a method is called, it is automatically passed an implicit argument that is reference to


the invoking object.
2. This implicit reference is called as this reference.
3. Instance variables and methods are automatically prefixed with this reference so that they
access correct object

13 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Book details – reducing number of setters and getters

class Book { Class Book {


private string title; private String title;
private string author; private string author;
private double cost; private souble cost;

public void SetTitle(String title){


this.title = title;
} public void SetDetails(string title
public string GetTitle(){ string author,
return title; double cost
} ){
this.title = title;
public void SetAuthor(string author){ this.author = author;
this.author = author; this.cost = cost;
} }
public string GetAuthor(){
return author;
}

public void SetCost(double cost){


this.cost = cost; public void GetDetails(){
} Console.WriteLine (title);
public double GetCost(){ Console.WriteLine (author);
return cost; Console.WriteLine (cost);
} }
}
}

14 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class TestBook {
static void Main() {
Book b1,b2;

// 1st book
b1 = new Book();

b1.SetTitle(“Complete Reference”); b1.SetDetails(“Complete Reference”,


b1.SetAuthor(“Herbert Schildt”);
”Herbert Schildt”,
b1.SetCost(450.00);
450.00);
// 2nd book
b2 = new Book();

b2.SetTitle(“ASP.NET”); b2.SetDetails(“ASP.NET”,
b2.SetAuthor(“Stephen Walther”); ”Stephen Walther”,
b2.SetCost(650.00);
650.00);

Console.WriteLine(“Book #1”);
Console.WriteLine (“----------------------------“);
Console.WriteLine (“\tTitle: “ + b1.GetTitle());
Console.WriteLine (“\tAuthor: “ + b1.GetAuthor()); b1.GetDetails();
Console.WriteLine (“\tCost: “ + b1.GetCost());

Console.WriteLine (); // empty line

Console.WriteLine (“Book #2”);


Console.WriteLine (“----------------------------“);
Console.WriteLine (“\tTitle: “ + b2.GetTitle());
Console.WriteLine (“\tAuthor: “ + b2.GetAuthor()); b2.GetDetails();
Console.WriteLine (“\tCost: “ + b2.GetCost());
}
}

15 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// this code reduces printing process

class TestBook2 {
static void Main() {
Book b1,b2;

// 1st book
b1 = new Book();
b1.SetTitle(“Complete Reference”);
b1.SetAuthor(“Herbert Schildt”);
b1.SetCost(450.00);

// 2nd book
b2 = new Book();
b2.SetTitle(“ASP.NET”);
b2.SetAuthor(“Stephen Walther”);
b2.SetCost(650.00);

Console.WriteLine (“Book #1”);


Console.WriteLine (“----------------------------“);
TestBook2.Print(b1);

Console.WriteLine (); // empty line

Console.WriteLine (“Book #2”);


Console.WriteLine (“----------------------------“);
TestBook2.Print(b2);
}

// static method – to invoke this method ; use “class name followed with method name”
public static void Print(Book b){
Console.WriteLine (“\tTitle: “ + b.GetTitle());
Console.WriteLine (“\tAuthor: “ + b.GetAuthor());
Console.WriteLine (“\tCost: “ + b.GetCost());
}

16 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// Array of objects
class TestBook2 {
static void Main() {
Book[] b;
b = new Book[3]; // array of 3 books

string title, author;


double cost;

for(int I =0; I<3; i++) {


Console.WriteLine (“Enter “ + (i+1) + “ “ + “Book Details”);
Console.WriteLine (“Title”);
b[0]
title = Console.ReadLine();
Console.WriteLine (“Author”); titlea ttt 0
author = Console.ReadLine(); author System.out.println(“Cost”);
Console.WriteLine(“Cost”); ccc cost
cost = double.Parse(
Console.ReadLine ()); b[1]

title tttt
// creating an object 1
author
aa
b[i] = new Book(); cccccost

// placing values
b[i].SetTitle(title); b[2]
b[i].SetAuthor(author); title tttt
b[i].SetCost(cost); 2
author
aa
} cccccost
for(int I = 0; i<3; i++){
Console.WriteLine (“Book # “ + (i+1) ); b
Console.WriteLine (“---------------------------“);
Console.WriteLine (“\tTitle: “ + b[i].GetTitle());
Console.WriteLine (“\tAuthor: “ + b[i].GetAuthor());
Console.WriteLine (“\tCost: “ + b[i].GetCost());
Console.WriteLine (); // empty line
}
}

17 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// Additional methods and providing validation logic


class Number {
private int n;
public bool SetN(int n){

validation
If(n>0 && n<150){
this.n = n;
return true;
}else{
Console.WriteLine (“Sorry.. !.. Invalid Number (required 1..150)”);
this.n=0;
return false;
}
}
public int GetN(){
return n;
}
additional methods (optional)
public int Square(){
return n*n;
}
public int Cube(){
return n*n*n;
}
public int Factorial(){
int f=1;
while(n>0){
f=f*n;
n=n-1;
}
return f;
}
public int NoOfDigits(){
string str = n.ToString();
return str.length();
}
}

18 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class TestNumber {
static void Main() {

Number nobj = new Number();

int n;
bool status;

Console.WriteLine (“Enter Number (1..150) “);


n = int.Parse(Console.ReadLine()); setters & getters

status = nobj.SetN(n);
if(status==true) {
Console.WriteLine (“Number: “ + nobj.GetN());
Console.WriteLine (“Square: “ + nobj.Square() + “, Cube: “ + nobj.Cube());
Console.WriteLine (“No.of digits: “ + nobj.NoOfDigits());
}
}
}
additional methods

19 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// Constructors

class DefaultConstructor { class DefaultConstructor {

private int v1; private int v1;


private double v2; private double v2;
private string v3; private string v3;

public void SetValues(int v1, public DefaultConstructor() {


double v2, v1 = 0; //default
String v3) { v2 = 0.0; //default
this.v1 = v1; v3 = null; //default
this.v2 = v2; }
this.v3 = v3;
} public void SetValues(int v1,
public void GetValues() { double v2,
Console.WriteLine ("v1=" + v1); string v3) {
Console.WriteLine ("v2=" + v2); this.v1 = v1;
Console.WriteLine ("v3=" + v3); this.v2 = v2;
} this.v3 = v3;
} }
public void GetValues() {
Console.WriteLine ("v1=" + v1);
Console.WriteLine ("v2=" + v2);
Console.WriteLine ("v3=" + v3);
DefaultConstructor d; }
}
D = new DefaultConstructor();

20 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

output
V1 0 V1 = 0
class TestDefaultConstructor {
static void Main() { V2 0.0 V2 = 0.0

V3 null V3 = null
DefaultConstructor d;

d = new DefaultConstructor();

d.GetValues();
output
Console.WriteLine(); //empty line V1 10 V1 = 10
V2 1.25
d.SetValues(10,1.25,"scott"); V2 = 1.25
d.GetValues(); V3 scott V3 = scott
}
}

21 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// Explicit Constructor

class InternetURL { class InternetURL {


private string url; private string url;

public InternetURL() { public InternetURL(string url) {


url = "http://www.google.co.in/index.html"; this.url = url;
} }

public void SetUrl(string url) { /*public void SetUrl(string url) {


this.url = url; this.url = url;
} }*/
public string GetUrl() {
return url; public string GetUrl() {
} return url;
} }
}
// In the main

InternetURL u; InternetURL u;
u = new InternetURL(); //u = new InternetURL(); // error
u = new InternetURL(“http://www.google.co.in/index.html");

22 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// Multiple Constructors – constructor overloading; the role of “this” keyword

class InternetURL {
private string url; class InternetURL {
private string url;
public InternetURL() {
url = null; public InternetURL() {
//or this("http://www.google.co.in/
url = “http://www.google.co.in/ index.html");
index.html"; }
}
public InternetURL(string url) {
public InternetURL(string url) {
this.url = url;
this.url = url;
}
}
public void SetUrl(string url) {
this.url = url; public void SetUrl(string url) {
} this.url = url;
public string GetUrl() { }
return url; public string GetUrl() {
} return url;
} }
}

// In the main

InternetURL u;
u = new InternetURL();
//or
u = new InternetURL(“http://www.google.co.in/index.html");

Note: If you want , some additional methods can also be provided.

Ex: Protocol(), Domain(), FileName() etc.

23 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Points to remember:

1. It is a function in the class that has the same name as the class name.
2. Purpose: to initialize variables, allocating memory and establishing database connections
etc.
3. A class can have 2 types of constructors: static and non-static
4. Non-static constructor is automatically called whenever an object of the class is created.
5. Static constructor is implicitly called whenever a class is loaded into the memory.
6. If no constructor is explicitly defined then C#.Net creates a constructor which takes no
parameters – Default Constructor.
7. A class can accommodate more than one non-static constructor – constructor overloading.
8. Multiple static constructors can’t be created.

Note: Once a constructor is created in the class, c# does not provide default constructor any
more. Every time you create an object of the class a constructor must be invoked otherwise
object cannot be created.

Non-Static Constructor Static Constructor

1. Access Level private/public no keyword


2. Name class name class name
3. Overloading possible not possible
4. Variables instance/non-static class/static
5. Invoking explicit implicit

Does really a constructor not return anything?

Of course, implicitly constructors return an object of the enclosing class type. Even then
a programmer should not return anything including void in its header, doing so is a compile-time
error.

24 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class Account { class Account {


non-static variables; static variables;

public Account() { static Account() {

initializing non-static initializing static


variables; variables;

} }
…. ….
…. ….
} }

25 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Destructors and Garbage Collection (death of objects)

What is garbage and garbage collection?

Variables and objects whose purpose is over in the program and are not referenced
further (or no longer being used) are treated as garbage in .NET.

The implicit process performed by the CLR (Common Language Runtime) whenever
microprocessor is free is called garbage collection and the method (which is a low -
priority thread) that runs now and then is called garbage collector.

We can’t predict exactly when the garbage collection takes place.

Destructor method

Before any object is garbage collected, CLR calls the DESTRUCTOR method implicitly.

class Account {
static variables;
non-static variables;

~Account() {

code to free the objects


before they are garbage
collected

}
….
….
}

26 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

1. A class can have only one destructor – destructors cannot be overloaded.


2. Destructor cannot be called. They are invoked automatically.
3. It doesn’t take modifier or have parameters.

Note: Destructors are not called when object goes out of scope. They are called before object is
garbage collected.

27 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// static and non-static members

VARIABLES
static/class

METHODS non-static/instance

CLASS

28 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class TestMembers { class TestMembers {


private int v1; //non-static private int v1; //non-static
private int v2; //non-static private static int v2; //static
} }

// In the main

TestMembers tm1, tm2;

// 1st object
tm1 = new TestMembers();
V1
// 2st object
tm2 = new TestMembers(); tm1

V2
V2
V1
V1 V1

V2 V2 tm2

V2
tm1 tm2

V2 V2

29 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class Account { class Account {


// non-static variables // non-static variables
private int no; private int no;
private string name; private string name;
private double balance; private double balance;

// static variable // static variable


private static double minBalance=500.00; private static double minBalance;

// non-static constructor // non-static constructor


public Account(int no, public Account(int no,
String name, String name,
double balance) { double balance) {
this.no=no; this.no=no;
this.name=name;
this.name=name;
this.balance=balance; this.balance=balance;
}
}
public void GetDetails() {
System.out.println("No: "+ no); // static constructor
System.out.println("Name: "+ name); static Account() {
System.out.println("Balance: "+ balance); minBalance=500.00;
} }
…..
// static method …..
public static double MinimumBalance() {
return minBalance;
}
}

30 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class TestAccount {
static void Main() {

System.out.print("Minimum Balance: ");


System.out.println(Account.MinimumBalance());

Account a;
a = new Account(100,"scott",5000);
a.GetDetails();
}
}

private

minBalance 500.00

minimumBalance()

System.out.println(Account.MinimumBalance());

31 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

//constants
class Account {

// non-static variables
private int no;
private String name;
private double balance;

//constant
//public static double minBalance=500.00;
public const double MIN_BALANCE=500.00;

// non-static constructor
public Account(int no,
String name,
double balance) { public
this.no=no;
MIN_BALANCE 500.00
this.name=name;
this.balance=balance;
}

public void GetDetails() {


System.out.println("No: "+ no);
System.out.println("Name: "+ name);
System.out.println("Balance: "+ balance);
}
}

// In the main

System.out.print("Minimum Balance: ");


System.out.println(Account.MIN_BALANCE);

32 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

//readonly
class Account {

// non-static variables
private int no;
private String name;
private double balance;

//constant
//public readonly double MIN_BALANCE=500.00;
public readonly static double MIN_BALANCE=500.00;

// non-static constructor
public Account(int no,
String name,
double balance) {
this.no=no;
this.name=name;
this.balance=balance;
}

public void GetDetails() {


System.out.println("No: "+ no);
System.out.println("Name: "+ name);
System.out.println("Balance: "+ balance);
}
}

// In the main
System.out.print("Minimum Balance: ");
System.out.println(Account.MIN_BALANCE);

Account a = new Account(100,"scott",5000);


System.out.println(a.MIN_BALANCE);

33 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

//readonly
class Account {

// non-static variables
private int no;
private String name;
private double balance;

//constant
public readonly static double MIN_BALANCE;

// non-static constructor
public Account(int no,
String name,
double balance) {
this.no=no;
this.name=name;
this.balance=balance;
}
// staticconstructor
static Account() {
MIN_BALANCE=500.00;
}
}

34 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Constant vs. ReadOnly

const :

1. Can’t be static. By default (implicitly) it is static.


2. Value is evaluated at compile time.
3. Initialized at declaration only.

readonly:

1. Can be either instance or static level.


2. Value is evaluated at run time.
3. Can be initialized in declaration or by code in the constructor.

35 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

// method overloading class Greetings {


private string name;
class Greetings { private string message;
private string name;
public Greetings(String name,
private string message;
String message) {
this.name=name;
public Greetings(String name,
this.message=message;
String message) { }
this.name=name;
this.message=message; public String wishes() {
} String str="Hello ! " + name;
str += "\n";
public String wishes() { str += "Many More Happy Returns
String str="Hello ! " + name; Of The Day On This " +
message;
str += "\n";
}
str += "Many More Happy Returns
Of The Day On This " +
public String wishesMore(int times) {
message; String str=””;
} for(int i=1; i<=times; i++) {
str += "Hello ! " + name;
str += "\n";
str += "Many More Happy Returns
public String wishesMore(int times) {
Of The Day On This " +
String str=””;
message;
for(int i=1; i<=times; i++) {
str += “\n\n”;
str += wishes();
}
str += “\n\n”;
return str;
}
}
return str;
}
}

36 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

class Greetings {
private String name;
private String message;

public Greetings(String name,


// In the main
String message) {
this.name=name;
Greetings g;
this.message=message;
g = new Greetings (“scott”,
}
“birthday”);
public String sayWishes() {
g.sayWishes();
String str="Hello ! " + name;
str += "\n";
//or
str += "Many More Happy Returns
Of The Day On This " +
g.sayWishes(3);
message;
}

public String sayWishes(int times) {


String str=””;
for(int i=1; i<=times; i++) {
str += "Hello ! " + name;
str += "\n";
str += "Many More Happy Returns
Of The Day On This " +
message;
str += “\n\n”;
}
return str;
}

37 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

Points to remember

What is method overloading?

When two or more methods in a class are created with the same name they are said to
be overloaded.

Or

Re-using the same method name with different arguments with the same or different
return type is known as method overloading.

How compiler identifies the method if different methods have same method name?

From the above definition, the different arguments means using the same method
name not only with different number of arguments but also the arguments with
different data types. Compiler identifies the method called by considering the method’s
number and type of arguments.

What is overloading for?

Overloading is a OOP technique to avoid the usage of several method names that
perform closely related operations/jobs.

What is method signature?

Method signature includes method name, number of arguments and type of arguments
and does not include return type. That is methods with a different types of return value
and having the same name will be considered as the same method and if exists in the
same class, compiler throws an error.

Note: It is one kind of polymorphism. This is also known as compile-time polymorphism.

Assignment: Product, Programmer

38 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

A few more topics will be included …coming soon…

39 Object Oriented Programing for support: ptsm.4u@gamil.com


Lab Excercise C Sharp Programs : By PTSM

40 Object Oriented Programing for support: ptsm.4u@gamil.com

You might also like