Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved."— Presentation transcript:

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

2 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 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 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 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

6 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

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

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

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

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

11 11 Object & Class SWE 316- Ahmed Youssef

12 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:

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

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

15 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:

16 - 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

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

18 - 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();

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

20 - 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 " ;

21 - 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();

22 Encapsulation Data Hiding Abstraction Security ؟ 22

23 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

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

25 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

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

27 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..

28 - 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; }

29 - 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

30 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

31 Constructor Example Constructor

32 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);

33 Constructors Constructor Calling the constructor

34 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

35 No-argument constructor

36 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()

37 equals example

38 Invoking equals method: equals invocation

39 toString example toString invocation

40 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”

41 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);

42 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

43 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;

44 Simple Example static field static method

45 Example (Part 1 of 4)

46 Example (Part 2 of 4)

47 Example (Part 3 of 4)

48 Example (Part 4 of 4)


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

Similar presentations


Ads by Google