Basic Object-Oriented Concepts

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

21-Aug-14 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
CSCI 143 OOP – Inheritance 1. What is Inheritance? A form of software reuse Create a new class from an existing class – Absorb existing class data and.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Chapter 10 Classes Continued
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Object Oriented Software Development
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Basic Object- Oriented Concepts Presented By: George Pefanis 21-Sep-15.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 32 Thanks for Lecture Slides: C How to Program by Paul Deital &
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
10-Nov-15 Java Object Oriented Programming What is it?
Peyman Dodangeh Sharif University of Technology Fall 2014.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming Paradigms Lecturer Hamza Azeem. What is PP ? Revision of Programming concepts learned in CPLB Learning how to perform “Object-Oriented Programming”
Inheritance and Access Control CS 162 (Summer 2009)
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Basic Object-Oriented Concepts – towards implementation CS3340.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
OOPS CONCEPT.  OOPS  Benefits of OOPs  OOPs Principles  Class  Object Objectives.
OOP Basics Classes & Methods (c) IDMS/SQL News
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
BY:- TOPS Technologies
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Introduction to Object-Oriented Concept
Chapter 3: Using Methods, Classes, and Objects
Advanced Programming in Java
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Java Programming Language
Java Programming Language
Chapter 11 Inheritance and Encapsulation and Polymorphism
Classes and Methods 15-Aug-19.
Presentation transcript:

Basic Object-Oriented Concepts CS3340

The goals of OOP Objectives:modular programming. reusable code/modules. inheritance. can define interfaces

OOP Conceptual Implementation Abstraction Class Encapsulation Object Information Hiding Polymorphism Hierarchy Class Object Inheritance Interface

Abstraction "Extracting the essential details about an item or group of items, while ignoring the unessential details.“ model defines an abstract view to the problem.

Example of Abstraction Example: Administration of employees in an institution. Description: The head of the administration comes to you and ask you to create a program which allows to administer the employees. Well, this is not very specific. For example, what employee information is needed by the administration? What tasks should be allowed?   Solution: Employees are real persons who can be characterized with many properties; very few are: name, size, date of birth, shape, social number, room number, hair color, hobbies. Not all of these properties are necessary to solve the administration problem. Only some of them are problem specific. Consequently you create a model of an employee for the problem. This model only implies properties which are needed to fulfill the requirements of the administration, for instance name, date of birth and social number. These properties are called the data of the (employee) model. Now you have described real persons with help of an abstract employee.

Levels of Abstraction- highest "Community of Objects that must interact in order to achieve their common goal" GOAL: Make sure you have a good design for Abstraction at the Highest level.

Mid-level Abstraction Grouping of Objects working together into a single unit

Low level abstraction Deals with an action/method inside of a Class.

Upstream/Downstream Abstraction Creation of Children Classes to further abstract related class details. When not to do downstream abstraction when abstracting based on a range of values e.g. height in People.     Should you split People into Tall, Medium and Short subclasses? If it is functional more usefull to have AND They values are treated differently when abstracting based on a limited set of values e.g. People has attribute gender.....should we split into subclasses Male, Female? Upstream The idea here is we have a class (or classes) that we create a parent for. Often not a good idea as used by programmers to fix a design flaw. Consider creating a interface before the creation of a real super-class.

Techniques to achieve abstraction Division into parts , “has-a” Division into specialization, “is-a” Multiple views

division into parts – “has-a” Goal: By "Divide and Conquer" type technique we try to take apart the item under examination into its constituent parts. sometimes this process is referred to as "has-a"... like "a car has a engine".

division into specializations – “is-a” Goal: By "Divide and Conquer" type technique we try to break down into more and more specialized units. sometimes referred to as "is-a" abstraction........A car is a vehicle.

Multiple Views Goal: By creating "multiple views" of the same item, you can uncover essential details. How does driver view a car? How does a passenger view a car? How about a mechanic? and the designer? the manufacuter?  

Encapsulation Enclosing all parts of an abstraction within a container Protects access to the encapsulated (hidden) data or operation Increases modularity. Language Specific Most languages like Java have a "protection type" that can be applied to data and operations. Publish access operations so users of a class are encoraged to use these and not directly/access data. getX(), setX() operations. In Java: Can do information hidding with protection type declarations of private, public, protected, package protected.

Information Hiding Hiding parts of the abstraction Example: Leaf class –only access the data through operations/methods

Polymorphism made possible by inheritance in which a name denotes instances of many different classes, as long as they are related by a common super-class. Example: public void paint() {          Iterator it = shapes.iterator();         while (it.hasNext()) {           // polymorphism: shape can refer to squares,            //circles, triangles, etc.          Shape shape = (Shape)shapes.next();         shape.draw(); } }

Are there better forms of polymorphism? a = BAD,  an Account can have either Person OR Corporation associated with it. Violates encapsulation b = GOOD, Use polymorphism via inheritance to represent the disjunction.

Inheritance A class inherits state and behavior from its superclass. powerful and natural mechanism for organizing & structuring software programs.

Concept: Classes are like Abstract Data Types An Abstract Data Type (ADT) bundles together: some data, representing an object or "thing" the operations on that data The operations defined by the ADT are the only operations permitted on its data Example: a CheckingAccount, with operations deposit, withdraw, getBalance, etc. Classes enforce this bundling together If all data values are private, a class can also enforce the rule that its defined operations are the only ones permitted on the data

Example of a class class Employee { // Fields private String name; //Can get but not change private double salary; // Cannot get or set // Constructor Employee(String n, double s) { name = n; salary = s; } // Methods void pay () { System.out.println("Pay to the order of " + name + " $" + salary); } public String getName() { return name; } // getter }

Approximate Terminology instance = object field = instance variable method = operation = class function sending a message to an object = calling a method

Inheritance a mechanism that enables one class to inherit all the behaviors and attributes of another class. subclass = a class that inherits from another class.  superclass = a class that is its inheritance to another class.

More on inheritance Note: Subclasses can override methods they have inherited if they want to change the corresponding behavior. For example, the method to calculate the Expected Lifespan for each Class of Dog, Cat, and Horse may be different from their superclass Four-Legged Animal. 

Inheritance: Classes form a hierarchy Classes are arranged in a treelike structure called a hierarchy Every class may have one or more subclasses

Another Example of a hierarchy—this one dealing with windows Container Panel ScrollPane Window Dialog Frame FileDialog A FileDialog is a Dialog is a Window is a Container

Concept: Objects inherit from superclasses A class describes fields and methods Objects of that class have those fields and methods But an object also inherits: the fields described in the class's superclasses the methods described in the class's superclasses A class is not a complete description of its objects!

Example of inheritance class Person { String name; int age; void birthday () { age = age + 1; } class Employee extends Person { double salary; void pay () { ...} } Every Employee has name and age fields and birthday method as well as a salary field and a pay method.

Concept: Objects must be created int n; does two things: It declares that n is an integer variable It allocates space to hold a value for n For a primitive, this is all that is needed Employee secretary; also does two things It declares that secretary is type Employee It allocates space to hold a reference to an Employee For an object, this is not all that is needed secretary = new Employee ( ); This allocate space to hold a value for the Employee Until you do this, the Employee is null

Notation: How to declare and create objects Employee secretary; // declares secretary secretary = new Employee (); // allocates space Employee secretary = new Employee(); // does both But the secretary is still "blank" (null) secretary.name = "Adele"; // dot notation secretary.birthday (); // sends a message

Notation: How to reference a field or method Inside a class, no dots are necessary class Person { ... age = age + 1; ...} Outside a class, you need to say which object you are talking to if (john.age < 75) john.birthday (); If you don't have an object, you cannot use its fields or methods!

Concept: this object Inside a class, no dots are necessary, because you are working on this object If you wish, you can make it explicit: class Person { ... this.age = this.age + 1; ...} this is like an extra parameter to the method You usually don't need to use this

Concept: A variable can hold subclass objects Suppose B is a subclass of A A objects can be assigned to A variables B objects can be assigned to B variables B objects can be assigned to A variables, but A objects can not be assigned to B variables Every B is also an A but not every A is a B You can cast: bVariable = (B) aObject; In this case, Java does a runtime check

Example: Assignment of subclasses class Dog { ... } class Poodle extends Dog { ... } Dog myDog; Dog rover = new Dog (); Poodle yourPoodle; Poodle fifi = new Poodle (); myDog = rover; // ok yourPoodle = fifi; // ok myDog = fifi; //ok yourPoodle = rover; // illegal yourPoodle = (Poodle) rover; //runtime check

Concept: Methods can be overridden class Bird extends Animal { void fly (String destination) { location = destination; } class Penguin extends Bird { void fly (String whatever) { } } So birds can fly. Except penguins.

Concept: Don't call functions, send messages Bird someBird = pingu; someBird.fly ("South America"); Did pingu actually go anywhere? You sent the message fly(...) to pingu If pingu is a penguin, he ignored it Otherwise he used the method defined in Bird You did not directly call any method You cannot tell, without studying the program, which method actually gets used The same statement may result in different methods being used at different times

Sneaky trick: How to use overridden methods class FamilyMember extends Person { void birthday () { // override birthday() in Person super.birthday (); // call overridden method givePresent (); // and add your new stuff }

Concept: Constructors make objects Every class has a constructor to make its objects Use the keyword new to call a constructor secretary = new Employee ( ); You can write your own constructors; but if you don’t, Java provides a default constructor with no arguments It sets all the fields of the new object to zero If this is good enough, you don’t need to write your own The syntax for writing constructors is almost like that for writing methods

Syntax for constructors Do not use a return type and a name; use only the class name You can supply arguments Employee (String theName, double theSalary) { name = theName; salary = theSalary; }

Trick: Give field and parameter the same name A parameter overrides a field with the same name But you can use this.name to refer to the field class Person { String name; int age; Person (String name, int age) { this.name = name; this.age = age; } } Using the same name is a common and useful convention

Internal workings: Constructor chaining If an Employee is a Person, and a Person is an Object, then when you say new Employee () The Employee constructor calls the Person constructor The Person constructor calls the Object constructor The Object constructor creates a new Object The Person constructor adds its own stuff to the Object The Employee constructor adds its own stuff to the Person

The case of the vanishing constructor If you don't write a constructor for a class, Java provides one (the default constructor) The one Java provides has no arguments If you write any constructor for a class, Java does not provide a default constructor Adding a perfectly good constructor can break a constructor chain You may need to fix the chain

Example: Broken constructor chain class Person { String name; Person (String name) { this.name = name; } } class Employee extends Person { double salary; Employee ( ) { salary = 12.50; } Java tries to execute an implicit super() at this point super(); cannot resolve symbol – constructor Person()

Fixing a broken constructor chain Special syntax: super(...) calls the superclass constructor When one constructor calls another, that call must be first class Employee { double salary; Employee (String name) { super(name); // must be first salary = 12.50; } } Now you can only create Employees with names This is fair, because you can only create Persons with names

Trick: one constructor calling another this(...) calls another constructor for this same class class Something { Something (int x, int y, int z) { // do a lot of work here } Something ( ) { this (0, 0, 0); } } It is poor style to have the same code more than once If you call this(...), that call must be the first thing in your constructor

Concept: You can control access class Person { public String name; private String age; protected double salary; public void birthday { age++; } } Each object is responsible for its own data Access control lets an object protect its data and its methods Access control is the subject of a different lecture

Concept: Classes can have fields and methods Usually a class describes fields (variables) and methods for its objects (instances) These are called instance variables and instance methods A class can have its own fields and methods These are called class variables and class methods There is exactly one copy of a class variable, not one per object Use the special keyword static to say that a field or method belongs to the class instead of to objects

Example of a class variable class Person { String name; int age; static int population; Person (String name) { this.name = name; this.age = 0; population++; }

Advice: Restrict access Always, always strive for a narrow interface Follow the principle of information hiding: the caller should know as little as possible about how the method does its job the method should know little or nothing about where or why it is being called Make as much as possible private Your class is responsible for it’s own data; don’t allow other classes to screw it up!

Advice: Use setters and getters class Employee extends Person { private double salary; private boolean male; public void setSalary (double newSalary) { salary = newSalary; } public double getSalary () { return salary; } public boolean isMale() { return male; } This way the object maintains control Setters and getters have conventional names: setDataName, getDataName, isDataName (booleans only)

Kinds of access Java provides four levels of access: public: available everywhere protected: available within the package (in the same subdirectory) and to all subclasses [default]: available within the package private: only available within the class itself The default is called package visibility In small programs this isn't important...right?

From Budd Book on OOP 1. Everything is an Object (in pure OOP) 2. Computation is done via Objects Communicating with each other by requesting objects to perform actions. At some point at least a few object need to perform some work besides passing on requests to other objects/agents.  3. Each Object has its own memory (and in pure OOP consists of other objects)  4. Every object is an instance of a class. 5. A Class is a repository for behavior associated with an object and the kind of information stored in an instances memory. 6. Classes are organized into a single rooted tree structure. Memory and behavior of an instance of a class is automatically available (inheritance) to any class associated with a descendant.