Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Slides:



Advertisements
Similar presentations
ICS 201 Inheritance Introduction to Computer Science
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Chapter 4 Defining Classes I Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Road Map Introduction to object oriented programming. Classes
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
Chapter 4 Defining Classes I Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java Objects and Classes. 3-2 Object Oriented Programming  An OO program models the application as a world of interacting objects.  A typical Java program.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Objects and Classes Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Inheritance A Review of Objects, Classes, and Subclasses.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Slides prepared by Rose Williams, Binghamton University Chapter 4 Defining Classes I.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Chapter 4 Defining Classes I Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
YG - CS Concept of Encapsulation What is encapsulation? - data and functions/methods are packaged together in the class normally.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Programming Logic and Design Seventh Edition
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Road Map Introduction to object oriented programming. Classes
Chapter 4: Writing Classes
Object Based Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Corresponds with Chapter 7
Defining Classes and Methods
Java Classes and Objects 3rd Lecture
Defining Classes and Methods
JAVA CLASSES.
Chapter 4 Defining Classes I
Object Oriented Programming in java
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
2.1 Introduction to Object-Oriented Programming
Chapter 4 Constructors Section 4.4
Presentation transcript:

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

A Java Program A Java program consists of one or more classes A Java class consists of one or more methods A Java method consists of one or more statements A Java Program Java classes Java Methods

3 Diagram of program structure A program consists of one or more classes Typically, each class is in a separate.java file Program File Class Variables Constructors Methods Variables Statements

4 Classes and Source Files Each class is stored in a separate file The name of the file must be the same as the name of the class, with the extension.java public class Car {... } Car.java By convention, the name of a class (and its source file) starts with a capital letter. (In Java, all names are case-sensitive.)

5 public class SomeClass Fields Constructors Methods } Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects Procedures for constructing a new object of this class and initializing its fields Actions that an object of this class can take (behaviors) { Class header SomeClass.java import... import statements

Object-Oriented Programming (OOP) Classes are the most important language feature that make object-oriented programming (OOP) possible Programming in Java consists of defining a number of classes Every program is a class All helping software consists of classes All programmer-defined types are classes Classes are central to Java

Decomposition of the large problem into small parts that can be solved separately. Why Object Oriented? Large Application 7

Class Definition Name Data members (Data) Methods (Operations) … 8

Class Definition Student StudentID FirstName LastName Address etc… RegisterForCourse DropCourse etc... 9

Class Definition A class definition is composed of two parts: Data members (Data part) Methods (Operations part) Example: define a class Employee

11 Object & Class SWE 316- Ahmed Youssef

12 Class: Car Object: a car Attributes(Data): String model Color color int numPassengers double amountOfGas Behaviors (Methods): Add/remove a passenger Get the tank filled Report when out of gas Attributes: model = “Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5 Behaviors:

Object & Class Student StudentID FirstName LastName Address etc… RegisterForCourse DropCourse etc... Student  Ahmed  Majed  Salem  Saad 13

Student Ahmed Mohamed Hail etc… RegisterForCourse DropCourse etc... Student StudentID FirstName LastName Address etc… RegisterForCourse DropCourse etc Object & Class

Object Declaration It is possible to declare several objects from a class: Class Employee e2 e1 e3 e4 Note: classes Employee and TestClass should be saved in the same directory String s2 s1 s3 s4 The same principle as:

- A Class Is a Type A class is a special kind of programmer-defined type, and variables can be declared of a class type A value of a class type is called an object or an instance of the class The following sentences are equivalent: “ e1 is of type Employee," “ e1 is an object of the class Employee," and “ e1 is an instance of the class Employee" Employee e2 e1 e3 e4

Main Class Employee Class 3. Manage object 1. Create objects from class e1 e2 e3 e4 2. objects 17

- Object Creation - new Operator The instruction : Employee e1; only declares e1. But the object is still not created. To create the object the operator new must be used: e1 = new Employee(); These can be combined as follows: Employee e1 = new Employee();

- Object Creation DeclarationCreation Question: What is the name of Employee e1? How to change the name of Employee e1? … next slide..

- Instance Variables and Methods … In order to refer to a particular instance variable, preface it with its object name as follows: objectName.instanceVar1 objectName.instanceVar2 Example: e1.name e1.age e1.salary To change the name of e1: e1.name = " Mohamed " ;

- Instance Variables and Methods … In order to invoke a method of a class, you need an object of that class: objectName.method1() objectName.method2(argument1) Example: e1.outputDetails();

Encapsulation Data Hiding Abstraction Security ؟ 22

Encapsulation allows the programmer to group data and the methods that operate on them together in one place, and to hide details from the user. In Java, hiding details is done by marking them private Encapsulation (data hiding) withDraw Deposit Transfer Print AccountNo AccountValue NameAddress Change Address withDraw any value 23

Encapsulation Person Vending Machine Buy Pepsi Sell (1 SR, Pepsi) Sell 24

Access Modifiers: public and private Instance variables and methods of a class can be declared public, or private Example: public String name; private int age; public void outputDetails{..} The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class

- public and private Modifiers … Illegal because we try to access a private member (age) from outside the class Employee

Problem.. It is considered good programming practice to make all instance variables private Question: how to access and modify the instance variables of Employee objects e1, e2, e3 and e4?.. answer.. Use accessor and mutaor methods …. next slide..

- Accessor and Mutator Methods … The methods that retrieve the data of fields are called accessors. The data can be accessed but not changed The name of an accessor method starts with the word get Example: public String getName() { return name; } The methods that modify the data of fields are called mutators. The name of a mutator method starts with the word set Example: public void setName(String n) { name = n; }

- Accessor and Mutator Methods (Example) Accessor method for instance variable name Mutator method for instance variable name Modifying the name of e1 using a mutator method

Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object: public ClassName(ParametersList){…} A constructor must have the same name as the class A constructor has no type returned, not even void Constructors are typically overloaded

Constructor Example Constructor

How Constructors are called A constructor is called when an object of the class is created using new ClassName objectName = new ClassName(anyArgs); Example: Employee e1 = new Employee( " Mohamed ", 20, 5000);

Constructors Constructor Calling the constructor

Include a No-Argument Constructor If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor in your class, Java will not provide this default constructor If you include any constructors in your class, be sure to provide your own no-argument constructor as well

No-argument constructor

The methods equals and toString The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal “ Note: You cannot use == to compare objects public boolean equals(ClassName objectName) The purpose of the toString method is to return a String value that represents the data in the object public String toString()

equals example

Invoking equals method: equals invocation

toString example toString invocation

40 Class variables Vs Primitive type variables int i = 15; Employee e1 = new Employee("Mohamed", 20, 5000); i is a variable of type integer that contain the value 15. e1 is a variable of type Employee that contains the address where the object is located. The object named by the variable is stored in some other location in memory i 15  e1 “Mohamed”

Static Methods A static method is one that can be used without a calling object. A static method still belongs to a class, and its definition is given inside the class definition. When a static method is defined, the keyword static is placed in the method header public static returnedType myMethod(parameters) {... } Static methods are invoked using the class name in place of a calling object returnedValue = MyClass.myMethod(arguments);

Static Variables Static variables can be declared and initialized at the same time private static int myStaticVariable = 0; If not explicitly initialized, a static variable will be automatically initialized to a default value boolean static variables are initialized to false Other primitive types static variables are initialized to the zero of their type Class type static variables are initialized to null It is always preferable to explicitly initialize static variables rather than rely on the default initialization

Static Variables A static variable should always be defined private, unless it is also a defined constant The value of a static defined constant cannot be altered, therefore it is safe to make it public In addition to static, the declaration for a static defined constant must include the modifier final, which indicates that its value cannot be changed public static final int BIRTH_YEAR = 1954; When referring to such a defined constant outside its class, use the name of its class in place of a calling object int year = MyClass.BIRTH_YEAR;

Simple Example static field static method

Example (Part 1 of 4)

Example (Part 2 of 4)

Example (Part 3 of 4)

Example (Part 4 of 4)