oop lecture1

10
Object Oriented Programming Lecture 1 Object Oriented Programming Eastern University, Dhaka Md. Raihan Kibria

Upload: shahriar-robbani

Post on 26-May-2015

207 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Oop lecture1

Object Oriented Programming

Lecture 1

Object Oriented Programming

Eastern University, DhakaMd. Raihan Kibria

Page 2: Oop lecture1

Why object oriented programming

Consider the following program written in C:

Page 3: Oop lecture1

#include <stdio.h>#include <math.h>#include <stdlib.h>

struct cgpa{int grades[3];

}ca;

float getCgpa1(struct cgpa cgpa){float sum = 0;int i = 0;for (i=0;i<3; i++){

sum += cgpa.grades[i];}return sum/3;

}

Page 4: Oop lecture1

float getCgpa2(struct cgpa cgpa){ float sum = 0; int i = 0; for (i=0;i<3; i++){ sum += cgpa.grades[i]; } return roundf(sum/3);}

Page 5: Oop lecture1

float getCgpa3(struct cgpa cgpa){ float sum = 0; int i = 0; for (i=0;i<3; i++){ sum += cgpa.grades[i]; } return abs(sum/3);}

int main(){printf ("%s", "a message to start\n");ca.grades[0] = 3;ca.grades[1] = 5;ca.grades[2] = 6;printf("%f\n", getCgpa1(ca));printf("%f\n", getCgpa2(ca));printf("%f\n", getCgpa3(ca));

}

Page 6: Oop lecture1

OOP goals

Maximize code re-use Minimize re-coding

Page 7: Oop lecture1

Same program in javapublic class Grade {

public static void main(String[] args) { System.out.println(new Grade1().getCgpa()); System.out.println(new Grade2().getCgpa()); System.out.println(new Grade3().getCgpa()); }}

class Grade1{ int[] grades = {3,5,6}; float sum;

protected void calculateSum(){ for (int i=0; i<grades.length; i++) sum += grades[i]; }

public float getCgpa(){ calculateSum(); return sum / grades.length; }}

class Grade2 extends Grade1{ public float getCgpa(){ calculateSum(); return Math.round(sum / grades.length); }}

class Grade3 extends Grade1{ public float getCgpa(){ calculateSum(); return (float)Math.floor(sum / grades.length ); }}

Page 8: Oop lecture1

How to start programming in OOP

ClassA class is a template

//a studentpublic class ClassDemo { String code; String name;}

Page 9: Oop lecture1

Entry pointpublic static void main(String[] args) {}e.g.//a studentpublic class ClassDemo { String code; String name; public static void main(String[] args){ ClassDemo demo = new ClassDemo(); demo.code = "1221232323"; demo.name = "Raihan Kibria"; System.out.println(demo.code); System.out.println(demo.name); }}

Page 10: Oop lecture1

How to compile

Install jdk

Compile:javac ClassDemo.java

How to run:java ClassDemo