Chapter 6: Introduction to Programming Techniques PDF

Document Details

CourteousSense5107

Uploaded by CourteousSense5107

University of Technology and Applied Sciences - Ibri

Tags

programming techniques java fundamentals object-oriented programming software engineering

Summary

This document is an introduction to different programming techniques, focusing on Java fundamentals, encapsulation, polymorphism, and inheritance, accompanied by concepts of object-oriented programming. It's a great resource for introductory software engineering studies.

Full Transcript

Chapter 6 Introduction to different programming techniques Chapter 6 Introduction to different Programming techniques Java fundamentals: encapsulation, polymorphism, inheritance Benefits of Object-oriented programming Chapter 6 Software Engineering and Java programming...

Chapter 6 Introduction to different programming techniques Chapter 6 Introduction to different Programming techniques Java fundamentals: encapsulation, polymorphism, inheritance Benefits of Object-oriented programming Chapter 6 Software Engineering and Java programming fundamentals Objectives Learning Outcome 1. Discuss the object-oriented 1. Demonstrate an understanding of programming paradigm and basics of current theories, models, and techniques programming tool (Java) that provide a basis for the software 2. Design and build simple GUI apps using lifecycle. programming tool (Java). 2. Develop Java programs with the Object Oriented features such as encapsulation, inheritance and polymorphism. Table 6.1: Objectives and Learning Outcomes of Chapter 6 6.1.1 What is software engineering? Software engineering is the process of planning, designing, developing, installing and maintaining a software product. Software engineer is in-charge of all the phases of development of working software applications. Figure 6.1 : Software Development Phases 6.2.1 Type of High level languages High level languages are of two types. Structured programming languages Using these languages, software is designed in terms of sequence of operations/functionality performed by the software. Object Oriented languages Using these languages, software is designed by dividing the system into Objects then each Object is populated with its data and required functionalities for that Object. EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 5 PROGRAMMING Figure 6.2 : Structured Vs Object Oriented EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 6 PROGRAMMING Contd… EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 7 PROGRAMMING Overview – Byte 1 2 3 4 5 6 7 8 8 Bit 1 2 3 4 5 6 7 8 One Byte 6.3 Data types Data type is an identification construct used in programming languages to identify specific type of data which will be stored in computer memory. It also refers to the size of memory allocated for that specific data type. Commonly used data types Character Size = 1 byte “x”, “y”, etc Integer Size = 2 bytes 2, 2309, 6 Float Size = 4 bytes 40.2, 363.89 Double Size = 8 bytes Large types of numeric values Void = no value Defining the function in a program 6.2.3 Structured vs. OOP approaches Structured programming Object Oriented Programming Focus on designing the system based on Focus on dividing the system based on sequence of functionalities Objects in the system Used for designing small to medium size Used for designing medium to large size software. software. Data is centralized and any function can Data is distributed on the basis of Objects access any data element. and the functions of that Object can only access its data. No security of data Data is secured because of encapsulation inside the objects. Difficult or impossible to re-use the code in Re-usability of code is very common. new software. Which helps to save the time, effort and cost of development of new software. Table 6.2: Difference between Structured and Object Oriented Programming EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 10 PROGRAMMING Object Oriented why? EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 11 PROGRAMMING 6.4 Classes Class is a model(template) of a type of similar objects. For example in CIMS, Software Engineers identified that they have to store data of 15,000 students of college. So programmers will create one class Student with all data and functionalities in the software and when software will be running, the college student affairs department will create 15000 objects of student class to store the data of every student. EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 12 PROGRAMMING 6.5 Objects Objects are the basic run-time entities in a system which have data and functions. Steps while designing system using OOP, The system is modelled into Objects. Then for each Object data & required functionalities are identified. The relationship among various objects in the system are also identified. For example in Advising & Registration system of College, Advisor, Student, Registrar, degree, semester, course etc are the objects. EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 13 PROGRAMMING Example Class Object Student Name: Sarah State / Data Gender: Female Profession: Engineer Work(): She works as an engineer in XYZ company Name Study(): She studies 2 hours a day Gender Profession Object Behavior / Functions Name: Adam Gender: Male Profession: Doctor Work(); Work(): He works as a Study(); Psychiatrists in XYZ hospital Study(): He just graduated Figure 6.3 : Example of Object and Class EECP4192N : SOFTWARE ENGINEER ING & HIGH LEVEL 15 PROGRAMMING REVIEW 1. Objects are entities which have only functions (T/F) 2. Structured code is more secure than object oriented.(T/F) 3. There can NOT be more than 1 class in a software application.(T/F) 4. What is an “object” in object oriented programming? 5. What is a “class”? EECP4192N: Software Engineering & High Level Programming 16 Student class Student Class studentId Name Seat_no Data/Constructor Email Salary selfAdviseCourses() Behavior/Functions selfRegisterCourses() EECP4192N: Software Engineering & High Level Programming 17 Keywords in Java Class Account { int a; int b; Public void setData(int a, int b){ a= a; b=b; } EECP4192N: Software Engineering & High Level Programming 18 Instance variable: set as “a” Keywords in Java and “b” Global variable: setData, also Class Account { argument for set data is int a; defined as “a” and “b” int b; Public void setData(int a, int b){ a= a; b=b; } EECP4192N: Software Engineering & High Level Programming 19 Keywords in Java The compiler gets confused whether the instance on the Class Account { left side of an int a; operator is an int b; instance variable or global variable Public void setData(int a, int b){ a= a; b=b; } EECP4192N: Software Engineering & High Level Programming 20 Keywords in Java Use keyword “this” to Class Account { differentiate instance int a; variable from local int b; variable Public void setData(int a, int b){ this.a= a; this.b=b; } Public static void main(string args[]){ Account obj = new Account(); } EECP4192N: Software Engineering & High Level Programming 21 Keywords in Java Keyword “this” is Class Account { replaced by the int a; object handler “obj” int b; Public void setData(int a, int b){ this.a= a; this.b=b; } Public static void main(string args[]){ Account obj = new Account(); obj.setData(2,3); } EECP4192N: Software Engineering & High Level Programming 22 Keywords in Java Keyword “this” is replaced by the object handler “obj” Public void setData(int a, int b){ obj.a= a; obj.b=b; } Public static void main(string args[]){ Account obj = new Account(); obj.setData(2,3); } EECP4192N: Software Engineering & High Level Programming 23 Keywords in Java Keyword “this” is replaced by the object handler “obj” Public void setData(int c, int d){ this.a= c; this.b=d; } Public static void main(string args[]){ Account obj1 = new Account(); obj1.setData(2,3); Account obj2 = new Account(); obj2.setData(4,3); } EECP4192N: Software Engineering & High Level Programming 24 Keywords in Java Keyword “this” is replaced by the object handler “obj” Public void setData(int c, int d){ obj1.a= c; obj1.b=d; } Public static void main(string args[]){ Account obj1 = new Account(); obj1.setData(2,3); Account obj2 = new Account(); obj2.setData(4,3); } EECP4192N: Software Engineering & High Level Programming 25 Keywords in Java Keyword “this” is replaced by the object handler “obj” Public void setData(int c, int d){ obj2.a= c; obj2.b=d; } Public static void main(string args[]){ Account obj1 = new Account(); obj1.setData(2,3); Account obj2 = new Account(); obj2.setData(4,3); } EECP4192N: Software Engineering & High Level Programming 26 1.5 Creating a class in Java public class Student { string studentId; string Name; int seat_no; String email; Data float salary; public Student(String id, String nam, int s, String e, float sal) { this.studentId = id; this.Name = nam; this.seat_no = s; Constructor this.email = e; The constructor is a method that is this.salary = sal; called when an object is created of a } class public void selfAdviseCourses() { System.out.println(“self advise”); } public void selfRegisterCourses() { Functions + Display System.out.println(“self regsiter”); } } EECP4192N: Software Engineering & High Level Programming 27 6.5.1 Creating objects for the class 1.Objects are created from classes. 2. Create as many objects you want. Student s1=new Student(“12J13125”,”John”, 12, “[email protected]”, 1500.5); EECP4192N: Software Engineering & High Level Programming 28 6.5.1 Creating objects for the class public class Student { private string studentId; public String Name; protected int seat_no; String email; protected float salary; public Student(String id, String nam, int s, String e, float sal) { this.studentId = id; this.Name = nam; this.seat_no = s; this.email = e; this.salary = sal; } public void selfAdviseCourses() { System.out.println(“self advise”); } public void selfRegisterCourses() { System.out.println(“self regsiter”); } Public static void main (string [args]){ Student s1=new Student(“12J13125”,”John”, 12, “[email protected]”, 1500.5); } EECP4192N: Software Engineering & High Level Programming 29 6.5.1 Creating objects for the class public class Student { private string studentId; public String Name; protected int seat_no; String email; protected float salary; public Student(String id, String nam, int s, String e, float sal) { this.studentId = id; this.Name = nam; this.seat_no = s; this.email = e; this.salary = sal; } public void selfAdviseCourses() { System.out.println(“self advise”); } public void selfRegisterCourses() { System.out.println(“self regsiter”); } Public static void main (string [args]){ Student obj =new Student(); obj.Student (“12J13125”,”John”, 12, “[email protected]”, 1500.5); } 30 6.5.2 Exercise Define a java class Lecturer which has ID, name, phone_number and address. The Lecturer can upload quiz and enter the marks. The data members of the class must be initialized using constructors. (Assume any access specifier). Create 2 objects for this class. EECP4192N: Software Engineering & High Level Programming 31 24/APRIL/2024 EECP4192N: Software Engineering & High Level Programming 32 Inheritance and Composition EECP4192N: Software Engineering & High Level Programming 33 6.6 Relationships between classes 6.6.1 Inheritance(type-of) Figure 6.4 : Example of Inheritance Relationship EECP4192N: Software Engineering & High Level Programming 34 6.6.1 Inheritance ‘is a’ / ‘type of’ relationship between classes, where one class acquires properties of another class. “extends” keyword is used in java to represent this. For example, in our college system CIMS, Foundation and Post Foundation students are type of student and they have some features in common while some are different. In Object oriented design and programming it is named as Inheritance relationship. EECP4192N: Software Engineering & High Level Programming 35 class ParentClass{ int a; void setData(int a) { this.a = a; } } class ChildClass extends ParentClass{ void showData() { System.out.println("Value of a is " + a); } } public class SingleInheritance { public static void main(String[] args) { ChildClass obj = new ChildClass(); obj.setData(100); obj.showData(); } EECP4192N: Software Engineering & High Level Programming 36 6.6.1 Inheritance It helps to reuse the code and establish a relationship between different classes. In Java, there are two classes: 1. Parent class ( Super or Base class) 2. Child class (Subclass or Derived class ) A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class. EECP4192N: Software Engineering & High Level Programming 37 Student ID, Name, cgpa Foundation Post Foundation Student Student Level-1, Level-2 TOFEL score Figure 6.5 : Example of Inheritance Relationship EECP4192N: Software Engineering & High Level Programming 38 Figure 6.6 : Example of Inheritance Relationship EECP4192N: Software Engineering & High Level Programming 39 6.6.2 Program structure: Inheritance //This is a super class public class Student { protected String ID; protected String Name; protected float cgpa; public Student(String I, String n, float c){ this.ID=I; this.Name=n; this.cgpa=c; } } EECP4192N: Software Engineering & High Level Programming 40 //Subclass of Student public class Fstudent extends Student { private int L1Score; private int L2Score; Foundation public FStudent(String I, String n, float c, int m1, int m2){ Student super(I,n,c); this.L1score=m1; Level-1, Level-2 this.L2Score=m2; } } Student //Another subclass of Student ID, Name, cgpa public class PFstudent extends Student I ,n, c { Post Foundation private float TOFEL; Student public PFStudent(String I, String n, float c, float t){ super(I,n,c); TOFEL score this. TOFEL=t; } } EECP4192N: Software Engineering & High Level Programming 41 6.7 Containment In a system if some class is identified as ‘has a’ / ‘part of’ another class then this relationship in Object oriented design and programming is called as containment. Is a Toyota Has a Inheritance Containment Vehicle Engine EECP4192N: Software Engineering & High Level Programming 42 Figure 6.6 : Containment hierarchy for bicycle-design EECP4192N: Software Engineering & High Level Programming 43 6.7.1 Program structure: Containment public class Engine { private int cylinders; private float enginePower; public Engine(int c, float ep){ this.cylinders=c; this.enginePower=ep; } } EECP4192N: Software Engineering & High Level Programming 44 //Making engine class part of Car class public class Car public class Engine { { private int cylinders; protected string color; private float enginePower; protected int maxSpeed; public Engine(int c, float ep){ this.cylinders=c; Engine E1; this.enginePower=ep; } } public Car(String c, int ms ){ this.color=c; this.maxSpeed=ms; E1= new Engine(4, 240.5); } } EECP4192N: Software Engineering & High Level Programming 45 Summary Fig 6.7 Summary of Inheritance and composition 46 6.8 Access Specifiers Access Modifiers Private Default Protected Public Fig 6.8: Visibility of different access specifiers EECP4192N: Software Engineering & High Level Programming 47 6.8 Access Specifiers An access modifier restricts the access of a class, constructor, data member, and method in another class. Used to control visibility Package in java Access Specifier Inside Inherited Other classes Other classes class classes inside package outside package Private √ × × × Protected √ √ × × Package(default) √ √ √ × Public √ √ √ √ Table 6.3: Visibility of different access specifiers EECP4192N: Software Engineering & High Level Programming 48 EECP4192N: Software Engineering & High Level Programming 49 Package 1 Package 2 Class A: Class D: w, z, m, p, private int w; float p; protected string x; float y; w, x, y, z, m, n, public int z; Class B extends (inherits) A: int m; w, x, y, z, m, n, Class C: private string n; w, x, y, z, m, n, EECP4192N: Software Engineering & High Level Programming 50 6.8.1 Exercise : Write a java class employee with data as employee code, name and phone no. 1. Make his employee code visible to only its class. 2. Name visible to all the classes in the application. 3. Phone no visible to all classes in same package. Access Inside Inherited Other classes Other classes Specifier class classes inside package outside package Private √ × × × Protected √ √ × × Package( √ √ √ × default) public √ √ √ √ 51 Table 6.4: Exercise answer 6.9 Polymorphism The word polymorphism means having many forms. Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. EECP4192N: Software Engineering & High Level Programming 52 6.9.1 Example : We have a class Polymorphism that has a method sound(). Since this is a generic class so we can’t give it an implementation like: Roar, Meow etc. We had to give a generic message. EECP4192N: Software Engineering & High Level Programming 53 Now lets say we two subclasses of Polymorphism class: Animal and Cat that extends Polymorphism class. EECP4192N: Software Engineering & High Level Programming 54 Public class Polymorphism { Public class Animal{ Public void (){ Public void sound(){ System.out.printIn("Neigh") Animal myAnimal = new Animal(); } myAnimal.sound(): } Output } Neigh EECP4192N: Software Engineering & High Level Programming 55 Public class Polymorphism { Public class Animal{ Public class Cat extends Animal{ Public void (){ Animal myAnimal = new Animal(); Public void sound(){ Public int getBreed(){ Animal myAnimal = new Animal(); System.out.printIn(" Neigh ") Return breed; myAnimal.sound(): myAnimal.eat(): } } } }Cat myCat = new Cat (); } MyCat.sound(); Output } Neigh } Neigh EECP4192N: Software Engineering & High Level Programming 56 Public class Polymorphism { Public class Animal{ Public class Cat extends Animal{ Public void (){ Animal myAnimal = new Animal(); Public void sound(){ Public void sound(){ Animal myAnimal = new Animal(); System.out.printIn(" Neigh ") System.out.printIn("Meow") myAnimal.sound(): myAnimal.eat(): } } } }Cat myCat = new Cat (); Public int getBreed(){ MyCat.sound(); Output Return breed; } } Neigh } Meow EECP4192N: Software Engineering & High Level Programming 57 sound() method will be called is determined at runtime so the example we gave above is a runtime polymorphism example. EECP4192N: Software Engineering & High Level Programming 58 6.9.3 Overloading and Overriding in Java Overloading happens at compile time while Overriding happens at run time. The most basic difference is that Overloading is being done in the same class Overriding base and child classes are required. Argument list should be different while doing method overloading. Argument list should be same in method Overriding. EECP4192N: Software Engineering & High Level Programming 59 6.9.3.1 Example : // Function overloading class ABC { public void demo (int a) { System.out.println (“single int argument”); } public void demo (int a, int b) { System.out.println (“two int arguments”); } public double demo(double a) { System.out.println(" single double argument”); } EECP4192N: Software Engineering & High Level Programming 60 6.9.3.2 Example : // Function overriding //Parent function class ABC { public void demo () { System.out.println (“single argument”); } // Function overriding: child class Letters extends ABC { public void demo () { System.out.println (“single int argument”); } EECP4192N: Software Engineering & High Level Programming 61 6.9.3. Differences between Overloading and Overriding in java Overloading Overriding Occurs within ONE class Occurs in TWO classes: super class and sub class i.e. Inheritance is involved Name of the method is the same but different Name and parameter are the same parameters Purpose: increase readability of the program Purpose: use the method in class which is already present in parent class Example of compile time polymorphism Example of run time polymorphism EECP4192N: Software Engineering & High Level Programming 62 6.9.4 Exercise Write a java class calc1 that should contain a function XY. XY can add a maximum of up to 4 numbers depending upon the number of arguments passed. Hint: Use function Overloading. EECP4192N: Software Engineering & High Level Programming 63 public class calc1 { static void XY(){ int add(int a, int b) { return a+b; } int add(int a, int b, int c) { Output: return a+b+c; 30 } 60 int add(int a, int b, int c,int d) 100 { return a+b+c+d; } public static void main(String []args) { calc1 obj = new calc1(); System.out.println(obj.add(10, 20)); System.out.println(obj.add(10, 20, 30)); System.out.println(obj.add(10, 20, 30,40)); } } EECP4192N: Software Engineering & High Level Programming 64 1.9.5 Exercise Write a class Car, that contains a function speedlimit() that returns the maximum speed of a car. By default, speed limit is 100. Extend two classes ford and Toyota from Car class and override the function speedlimit. The speed limit for ford is 140 and for Toyota is 120. EECP4192N: Software Engineering & High Level Programming 65 public class Car { public class Ford extends Car { public class Toyata extends Car public int speedLimit() public int speedLimit() { { { public int speedLimit() return 100; return 150; } { } } return 120; } } } EECP4192N: Software Engineering & High Level Programming 66 6.9.5 Advantages and Disadvantages of Polymorphism Advantages: Programmers code can be reused via Polymorphism Supports a single variable name for multiple functions Disadvantages: Polymorphism in run time will lead to the performance problem where the system has to determine which process or variable to invoke so that the performance is effectively diminished as decisions are taken at run time. The readability of the program is diminished by polymorphism. EECP4192N: Software Engineering & High Level Programming 67 6.10 Software Reusability In software development process, specifications, designs, tests cases, data, prototypes, plans, documentation, frameworks, and templates can be reused but main importance is of software code reusability. EECP4192N: Software Engineering & High Level Programming 68 6.10.1 Reusability in Java In Java Packages and classes are reused. Inheritance and containment are methods to implement reusability. INHERITANCE CONTAINMENT EECP4192N: Software Engineering & High Level Programming 69 6.10.2 Case study: Fire Alarm Question: Read the case study below for a Fire Alarm System and solve it using with Object Oriented Approach{Identify two classes with their data and functions }. The owner of a large multi-storied building wants to have a computerized fire alarm system for his building. Smoke detectors and fire alarms would be placed in each room of the building. The fire alarm system would monitor the status of these smoke detectors. Whenever a fire condition is reported by any of the smoke detectors, the fire alarm system should determine the location at which the fire condition is reported by any of the smoke detectors. (contd…) EECP4192N: Software Engineering & High Level Programming 70 Example Case study (contd…) The fire alarm system should determine the location at which the fire condition has occurred and then sound the alarms only in the neighboring locations. The fire alarm system should also flash an alarm message on the computer console. Firefighting personnel manage the console round the clock. After a fire condition has been successfully handled, the fire alarm system should support resetting the alarms by the firefighting personnel. EECP4192N: Software Engineering & High Level Programming 71 6.11.0 Object-Oriented Approach: class detector –Data: detector_status, detector_locs –Functionality: scan_detectors(), get_detector_location(), report_fire_location(); class alarm –Data: alarm_status, alarm_locs, neighbor-alarm –Functionality: determine_neighbor(); ring_alarm(); reset_alarm(); EECP4192N: Software Engineering & High Level Programming 72 6.11.1 UML Diagrams Unified Modelling Language Way to visually represent the architecture, design, and implementation of complex software systems. Diagrams are organized into two distinct groups: structural diagrams and behavioral or interaction diagrams. Some examples of Structural UML diagrams Class diagram Object diagram Deployment diagram Some examples of behavioral UML diagrams Use case diagram Activity diagram Sequence diagram EECP4192N: Software Engineering & High Level Programming 73 6.11.1 UML Diagrams EECP4192N: Software Engineering & High Level Programming 74 6.11.1 UML Diagrams EECP4192N: Software Engineering & High Level Programming 75 6.11.1 UML Diagrams Unified Modelling Language Way to visually represent the architecture, design, and implementation of complex software systems. Diagrams are organized into two distinct groups: structural diagrams and behavioral or interaction diagrams. Some examples of Structural UML diagrams Class diagram Object diagram Deployment diagram Some examples of behavioral UML diagrams Use case diagram Activity diagram Sequence diagram EECP4192N: Software Engineering & High Level Programming 76 6.11.1 UML Diagrams EECP4192N: Software Engineering & High Level Programming 77 Diagrams to be familiar with: Class diagram: show the static structure of a system, including classes, their attributes and behaviors, and the relationships between each class. Object diagram : show examples of data structures at a specific time. You could use a class diagram to show a structure and then use object diagrams as test cases to verify the completeness of your class diagram. Deployment diagram: show how software is deployed on hardware components in a system. Use case diagram: model how users, displayed as stick figures called “actors,” interact with the system. Activity diagram: visualize the steps performed in a use case—the activities can be sequential, branched, or concurrent. Sequence diagram: sometimes referred to as an event diagram or an event scenario, shows the order in which objects interact. EECP4192N: Software Engineering & High Level Programming 78 6.12 Java Frameworks Frameworks are large bodies of pre-written code to which you add your own code in order to solve a problem. You make use of a framework by calling its methods, using inheritance etc. Some examples of popular framework Spring framework: core features of the Spring Framework can be used in developing any Java application. Companies like Netflix, amazon, ebay use this for application development. Hibernate ORM is a stable object-relational mapping framework for Java. It makes better communication possible between the Java programming language and relational database management systems (RDBMS). Used by oracle, Dell, IBM Struts:This fully-featured Java web application framework that allows the developers to create an easy-to-maintain Java application. JavaServer Faces [JSF]: developed by Oracle for building user interfaces for Java-based web applications. EECP4192N: Software Engineering & High Level Programming 79 Additional information(Research) Code reusability in software programming- Publication by Miquel Canal- Case study http://treeindev.net/article/code-reusability-software-programming Oriented Design & Programming-Lecture notes- University of Mississippi https://john.cs.olemiss.edu/~hcc/csci581oo/notes/budd10.html "A Study of Importance of UML diagrams: With Special Reference to Very Large-sized Projects“ https://www.researchgate.net/publication/322991896_A_Study_of_I mportance_of_UML_diagrams_With_Special_Reference_to_Very_Lar ge-sized_Projects EECP4192N: Software Engineering & High Level Programming 80

Use Quizgecko on...
Browser
Browser