defining classes-and-objects-1.0

53
Classes and Objects Classes and Objects Defining Classes Defining Classes and Objects and Objects

Upload: bg-java-ee-course

Post on 22-May-2015

2.185 views

Category:

Technology


5 download

DESCRIPTION

An introduction to the basics of OOP - declaring and using classes

TRANSCRIPT

Page 1: Defining classes-and-objects-1.0

Classes and ObjectsClasses and Objects

Defining Classes Defining Classes and Objectsand Objects

Page 2: Defining classes-and-objects-1.0

ContentsContents

• Defining simple classesDefining simple classes

• Using classesUsing classes

• ConstructorsConstructors

• PropertiesProperties

• Static MembersStatic Members

Page 3: Defining classes-and-objects-1.0

Defining Defining SSimple imple CClasses lasses

Page 4: Defining classes-and-objects-1.0

What a Class Should Contain?What a Class Should Contain?

• Mechanism to create new object of the Mechanism to create new object of the current type (for non-abstract classes)current type (for non-abstract classes)

• Information about base classesInformation about base classes

• Properties that are relevant to the problemProperties that are relevant to the problem

• Operations that can be used (methods)Operations that can be used (methods)

Page 5: Defining classes-and-objects-1.0

Defining ClassesDefining Classes

• Simple class definition:Simple class definition:

public class Cat extends Animal {public class Cat extends Animal { private String name;private String name;

public Cat(String name) {public Cat(String name) { this.name = name;this.name = name; }}

public void SayMiau() {public void SayMiau() { System.out.printf("Cat %s said: Miauuuuuu!", name);System.out.printf("Cat %s said: Miauuuuuu!", name); }}}}

ClassClassClassClass

FieldFieldFieldField

ConstructorConstructorConstructorConstructor

MethodMethodMethodMethod

Page 6: Defining classes-and-objects-1.0

Elements of Class DefinitionsElements of Class Definitions

• Class declarationClass declaration

• Can be followed by inherited class or Can be followed by inherited class or implemented interfacesimplemented interfaces

• Constructors (static or instance)Constructors (static or instance)

• Fields (static or instance)Fields (static or instance)

• Properties (static or instance)Properties (static or instance)

• Methods (static or instance)Methods (static or instance)

• Events (static or instance)Events (static or instance)

Page 7: Defining classes-and-objects-1.0

Defining Defining SSimple imple CClasseslassesExamplesExamples

Page 8: Defining classes-and-objects-1.0

Task: Define a ClassTask: Define a Class

• You should define a simple class that You should define a simple class that represents a catrepresents a cat

• The cat should have a nameThe cat should have a name

• You should be able to view and change the You should be able to view and change the name of the catname of the cat

• The cat should be able to mewThe cat should be able to mew

• If there is no name assigned to the cat it If there is no name assigned to the cat it should be named “should be named “NastradinNastradin””

Page 9: Defining classes-and-objects-1.0

Defining Simple ClassDefining Simple Class

• Our pet as a class:Our pet as a class:

public class Cat {public class Cat { private String name;private String name;

public String getName() {public String getName() { return this.name;return this.name; }}

public void setName(String name) {public void setName(String name) { this.name = name;this.name = name; }}

// (The example continues on the next slide)// (The example continues on the next slide)

Class definitionClass definitionClass definitionClass definition

Field definitionField definitionField definitionField definition

Property getterProperty getterProperty getterProperty getter

Property setterProperty setterProperty setterProperty setter

Page 10: Defining classes-and-objects-1.0

Defining Simple Class (2)Defining Simple Class (2)

public Cat() {public Cat() { this.name = "Nastradin";this.name = "Nastradin"; }}

public Cat(String name) {public Cat(String name) { this.name = name;this.name = name; }}

public void public void ssayMiau() {ayMiau() { System.out.printf(System.out.printf(

"Cat %s said: Miauuuuuu!%n", name);"Cat %s said: Miauuuuuu!%n", name); }}} }

Method Method definitiondefinitionMethod Method

definitiondefinition

Constructor Constructor definitiondefinition

Constructor Constructor definitiondefinition

Constructor Constructor definitiondefinition

Constructor Constructor definitiondefinition

Page 11: Defining classes-and-objects-1.0

Using Using CClasseslasses

Page 12: Defining classes-and-objects-1.0

What to Do With Classes?What to Do With Classes?

• Create new instanceCreate new instance

• Set / Get properties of the classSet / Get properties of the class

• Execute methodsExecute methods

• Handle eventsHandle events

• Create new classes derived from existing Create new classes derived from existing onesones

Page 13: Defining classes-and-objects-1.0

How to Use Classes?How to Use Classes?

1.1. Create instanceCreate instance

• Initialize fieldsInitialize fields

2.2. Manipulate instanceManipulate instance

• Set / Get propertiesSet / Get properties

• Execute methodsExecute methods

• Handle eventsHandle events

3.3. Release occupied resources – it’s done in Release occupied resources – it’s done in most cases automaticallymost cases automatically

Page 14: Defining classes-and-objects-1.0

Using Using CClasseslasses

ExampleExample

Page 15: Defining classes-and-objects-1.0

Task: Cat MeetingTask: Cat Meeting

• Create 3 catsCreate 3 cats

• First should be named “Garfield”, second – First should be named “Garfield”, second – “Tom” and last – no name“Tom” and last – no name

• Add all cats in arrayAdd all cats in array

• Iterate through the array and make every cat Iterate through the array and make every cat to mewto mew

• NOTE: Use Cat class from the previous NOTE: Use Cat class from the previous example!example!

Page 16: Defining classes-and-objects-1.0

Manipulating Class InstancesManipulating Class Instances

public static void main(String[] args) {public static void main(String[] args) { Scanner input = new Scanner(System.in);Scanner input = new Scanner(System.in); System.out.println("Write first cat name: ");System.out.println("Write first cat name: "); String firstCatName = input.nextLine();String firstCatName = input.nextLine(); // Assign cat name with a constructor// Assign cat name with a constructor Cat firstCat = new Cat(firstCatName);Cat firstCat = new Cat(firstCatName);

System.out.println("Write second cat name: ");System.out.println("Write second cat name: "); Cat secondCat = new Cat();Cat secondCat = new Cat(); // Assign cat name with a property// Assign cat name with a property secondCat.setName(input.nextLine());secondCat.setName(input.nextLine());

// Create a cat with a default name// Create a cat with a default name Cat thirdCat = new Cat();Cat thirdCat = new Cat();

• Sample task solution:Sample task solution:• Sample task solution:Sample task solution:

// (The example continues on the next slide)// (The example continues on the next slide)// (The example continues on the next slide)// (The example continues on the next slide)

Page 17: Defining classes-and-objects-1.0

Manipulating Class Instances Manipulating Class Instances (2)(2)

Cat[] cats = new Cat[] {Cat[] cats = new Cat[] { firstCat, firstCat, secondCat, secondCat, thirdCatthirdCat

};};

for(Cat cat for(Cat cat :: cats) cats) { { cat.SayMiau(); cat.SayMiau(); }}}}

Page 18: Defining classes-and-objects-1.0

Using Using CClasseslasses in Java in Java

Live DemoLive Demo

Page 19: Defining classes-and-objects-1.0

ConstructorsConstructorsDefining and Using Constructors in Defining and Using Constructors in

the Classesthe Classes

Page 20: Defining classes-and-objects-1.0

What is a Constructor?What is a Constructor?

• Creates a new instance of an objectCreates a new instance of an object

• Executes automatically when we create new Executes automatically when we create new objectsobjects

• Must initialize fields of the instanceMust initialize fields of the instance

Page 21: Defining classes-and-objects-1.0

Defining ConstructorsDefining Constructors

• Constructor has the same name as the classConstructor has the same name as the class• Has no return typeHas no return type• Can be private, protected, public or Can be private, protected, public or defaultdefault• Can have parametersCan have parameters

public class Pointpublic class Point {{ private int xCoord;private int xCoord; private int yCoord;private int yCoord;

public Point() public Point() { { // // SSimple default constructorimple default constructor xCoord = 0;xCoord = 0; yCoord = 0;yCoord = 0; }}

// More code ...// More code ...} }

Page 22: Defining classes-and-objects-1.0

ConstructorsConstructorsExamplesExamples

Page 23: Defining classes-and-objects-1.0

Defining ConstructorsDefining Constructors

public class Person {public class Person {

private String name;private String name; private int age;private int age;

// Default constructor// Default constructor public Person() {public Person() { this.name = null;this.name = null; this.age = 0;this.age = 0; }}

// Constructor with parameters// Constructor with parameters public Person(String name, int age) {public Person(String name, int age) { this.name = name;this.name = name; this.age = age;this.age = age; }} //More code ... //More code ... } }

Page 24: Defining classes-and-objects-1.0

Indirect ConstructorsIndirect Constructors

NOTE: Be careful when using inline initialization !NOTE: Be careful when using inline initialization !

ppublic class ClockAlarm {ublic class ClockAlarm {

private int hours = 0; // Inline field initializatioprivate int hours = 0; // Inline field initializationn private int minutes = 0; // Inline field private int minutes = 0; // Inline field initializationinitialization

// Default constructor// Default constructor public ClockAlarm() {public ClockAlarm() { }}

// Constructor with parameters// Constructor with parameters ppublic ClockAlarm(int hours, int minutes) {ublic ClockAlarm(int hours, int minutes) { this.hours = hours;this.hours = hours; this.minutes = minutes;this.minutes = minutes; }} // More code ...// More code ...} }

Page 25: Defining classes-and-objects-1.0

Advanced TechniquesAdvanced Techniques

Reusing constructorsReusing constructorspublic class Point {public class Point { // Definition of fields (member variables)// Definition of fields (member variables) private int xCoord;private int xCoord; private int yCoord;private int yCoord; private String name;private String name;

// The default constructor calls the other constructor// The default constructor calls the other constructor public Point() {public Point() { this(0, 0);this(0, 0); }}

// Constructor to parameters// Constructor to parameters public Point(int xCoord, int yCoord) {public Point(int xCoord, int yCoord) { this.xCoord = xCoord;this.xCoord = xCoord; this.yCoord = yCoord;this.yCoord = yCoord; name = String.format("(%d,%d)", this.xCoord, name = String.format("(%d,%d)", this.xCoord,

this.yCoord);this.yCoord); }} // More code ...// More code ...} }

Page 26: Defining classes-and-objects-1.0

ConstructorsConstructorsLive DemoLive Demo

Page 27: Defining classes-and-objects-1.0

PropertiesPropertiesDefining and Using PropertiesDefining and Using Properties

Page 28: Defining classes-and-objects-1.0

What is a PropertyWhat is a Property

• Properties are not exactly part of Java.Properties are not exactly part of Java.• They are good practice and important part of They are good practice and important part of

OOPOOP• Expose object's data to the outside worldExpose object's data to the outside world• Control the way data is manipulatedControl the way data is manipulated• Define if data can be:Define if data can be:• ReadRead

• WrittenWritten

• Read and writtenRead and written

• Gives good level of abstractionGives good level of abstraction

Page 29: Defining classes-and-objects-1.0

Defining PropertiesDefining Properties

• Properties is defined with:Properties is defined with:• Field with Field with privateprivate access modifier access modifier• GetterGetter and/or and/or SetterSetter method method• gettergetter – method returning the value of the – method returning the value of the

fieldfield• settersetter – method setting the value of the field – method setting the value of the field

public class Pointpublic class Point {{ private int xCoord;private int xCoord;

public int getXCoord() {public int getXCoord() { return xCoord;return xCoord; }} public void setXCoord(int coord) {public void setXCoord(int coord) { xCoord = coord;xCoord = coord; }}} }

Page 30: Defining classes-and-objects-1.0

PropertiesPropertiesExamplesExamples

Page 31: Defining classes-and-objects-1.0

Capsulate FieldsCapsulate Fields

public class Pointpublic class Point { { privateprivate int xCoord; int xCoord; privateprivate int yCoord; int yCoord;

// constructing code ...// constructing code ...

public int getXCoord() {public int getXCoord() { return this.xCoord;return this.xCoord; }} public void setXCoord(int value) {public void setXCoord(int value) { this.xCoord = value;this.xCoord = value; }} public int getpublic int getYYCoord() {Coord() { return this.return this.yyCoord;Coord; }} public void setpublic void setYYCoord(int value) {Coord(int value) { this.this.yyCoord = value;Coord = value; }} // More code ...// More code ...} }

Fields are Fields are encapsulated as encapsulated as private membersprivate members

Fields are Fields are encapsulated as encapsulated as private membersprivate members

Getters and Setter Getters and Setter allow controlled allow controlled

access to the private access to the private fieldsfields

Getters and Setter Getters and Setter allow controlled allow controlled

access to the private access to the private fieldsfields

Page 32: Defining classes-and-objects-1.0

Dynamic PropertiesDynamic Properties

• You can create properties that are not You can create properties that are not bound to a class fieldbound to a class field

public class Rectangle {public class Rectangle { private float width;private float width; private float height;private float height;

public Rectangle(float width, float height) {public Rectangle(float width, float height) { // Some initialization code// Some initialization code }}

public float getArea() {public float getArea() { return width * height;return width * height; }}} }

Page 33: Defining classes-and-objects-1.0

PropertiesPropertiesLive DemoLive Demo

Page 34: Defining classes-and-objects-1.0

Static MembersStatic MembersStatic vs. Instance Fields, Methods Static vs. Instance Fields, Methods

and Propertiesand Properties

Page 35: Defining classes-and-objects-1.0

What is What is staticstatic??

• Static items are associated with a type rather Static items are associated with a type rather than with an instancethan with an instance

• Can be used withCan be used with

• FieldsFields

• MethodsMethods

• ConstructorConstructor

Page 36: Defining classes-and-objects-1.0

Static vs. Non-StaticStatic vs. Non-Static

• StaticStatic: Associated with a type, not with an : Associated with a type, not with an instanceinstance

• Non-StaticNon-Static: the opposite: the opposite

• StaticStatic: Initialized when type is used for the : Initialized when type is used for the first time (Pay attention!)first time (Pay attention!)

• Non-StaticNon-Static: Initialized when the constructor : Initialized when the constructor is calledis called

Page 37: Defining classes-and-objects-1.0

Static MembersStatic MembersExamplesExamples

Page 38: Defining classes-and-objects-1.0

Static Members – ExampleStatic Members – Example

public class Sequence {public class Sequence { private static int currentValue = 0;private static int currentValue = 0;

private Sequence() { // Deny instantiation of this classprivate Sequence() { // Deny instantiation of this class }}

public static int nextValue() {public static int nextValue() { currentValue++;currentValue++; return currentValue;return currentValue; }}}}public class TestSequence {public class TestSequence { public static void main(String[] args) {public static void main(String[] args) { System.out.printf("Sequence[1..3]: %d, %d, %d ", System.out.printf("Sequence[1..3]: %d, %d, %d ",

Sequence.nextValue(), Sequence.nextValue(), Sequence.nextValue(), Sequence.nextValue(), Sequence.nextValue());Sequence.nextValue());

}}}}

Page 39: Defining classes-and-objects-1.0

Static MembersStatic MembersLive DemoLive Demo

Page 40: Defining classes-and-objects-1.0

Creating Static MethodsCreating Static Methods

public class Fractionpublic class Fraction {{ private int numerator;private int numerator; private int denominator;private int denominator;

public Fraction(int num, int denom)public Fraction(int num, int denom) {{ this.numerator = num;this.numerator = num; this.denominator = denom;this.denominator = denom; }}

public public staticstatic Fraction Parse( Fraction Parse(SString val)tring val) {{ SString[] parts = val.tring[] parts = val.ssplit(plit(""//"");); int num = Integer.parseInt(parts[0]);int num = Integer.parseInt(parts[0]); int denom = Integer.parseInt(parts[1]);int denom = Integer.parseInt(parts[1]); Fraction result = new Fraction(num, denom);Fraction result = new Fraction(num, denom); return result;return result; }}}}

Page 41: Defining classes-and-objects-1.0

Calling Static MethodsCalling Static Methods

• Parsing custom type from stringParsing custom type from string

public static void main(String[] args) {public static void main(String[] args) { String fractStr = "2/3";String fractStr = "2/3";

try {try { fraction = fraction = Fraction.ParseFraction.Parse(fractStr);(fractStr);

System.out.println("fraction = " + fraction);System.out.println("fraction = " + fraction); }} catch (Exception ex) {catch (Exception ex) { System.out.println("Can not parse the fraction.");System.out.println("Can not parse the fraction."); }}}}

Page 42: Defining classes-and-objects-1.0

Parsing FractionsParsing FractionsLive DemoLive Demo

Page 43: Defining classes-and-objects-1.0

SummarySummary

• Classes define specific structure for Classes define specific structure for the objectsthe objects

• Objects are class' instances and use Objects are class' instances and use this structurethis structure

• Constructors initialize object stateConstructors initialize object state

• Properties encapsulate fieldsProperties encapsulate fields

• Static methods are associated with a typeStatic methods are associated with a type

• Non-static – with and instance (object)Non-static – with and instance (object)

Page 44: Defining classes-and-objects-1.0

Lecture TopicLecture Topic

Questions?Questions?

Page 45: Defining classes-and-objects-1.0

ExercisesExercises

1.1. Define class Define class StudentStudent that holds information that holds information about students: full name, course, specialty, about students: full name, course, specialty, university, email, phone. Use enumeration for university, email, phone. Use enumeration for the specialties and universities.the specialties and universities.

2.2. Define several constructors for the class Define several constructors for the class StudentStudent that take different sets of arguments that take different sets of arguments (the full information about the student or part of (the full information about the student or part of it). The unknown data fill with it). The unknown data fill with nullnull or or 00..

3.3. Add a static field in the Add a static field in the StudentStudent class to hold class to hold the total number of instances ever created. To the total number of instances ever created. To keep this value current, modify the constructors keep this value current, modify the constructors as necessary.as necessary.

Page 46: Defining classes-and-objects-1.0

Exercises (2)Exercises (2)

4.4. Add a method in the class Add a method in the class StudentStudent for for displaying all information about the student.displaying all information about the student.

5.5. Use properties to encapsulate data inside the Use properties to encapsulate data inside the StudentStudent class. class.

6.6. Write a class Write a class StudentTestStudentTest to test to test the the functionality of the functionality of the StudentStudent class: Create class: Create several students and display all information several students and display all information about them.about them.

7.7. Add a static constructor in the Add a static constructor in the StudentTestStudentTest class that creates several instances of the class class that creates several instances of the class StudentStudent and holds them in static variables. and holds them in static variables. Create a static property to access them. Write a Create a static property to access them. Write a test program to print them.test program to print them.

Page 47: Defining classes-and-objects-1.0

Exercises (3)Exercises (3)

8.8. We are given a school. In the school there are We are given a school. In the school there are classes of students. Each class has a set of classes of students. Each class has a set of teachers. Each teacher teaches a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique disciplines. Students have name and unique class number. Classes have unique text class number. Classes have unique text identifier. Teachers have name. Disciplines have identifier. Teachers have name. Disciplines have name, number of lectures and number of name, number of lectures and number of exercises. Both teachers and students are exercises. Both teachers and students are persons.persons.

Your task is to model the school with Java Your task is to model the school with Java classes. You need to define the classes along classes. You need to define the classes along with their fields, properties and constructors.with their fields, properties and constructors.

Page 48: Defining classes-and-objects-1.0

Exercises (4)Exercises (4)

9.9. Define a class that holds information about Define a class that holds information about mobile phone device: model, manufacturer, mobile phone device: model, manufacturer, price, owner, battery characteristics (model, price, owner, battery characteristics (model, hours idle and hours talk) and display hours idle and hours talk) and display characteristics (size and colors). Define 3 characteristics (size and colors). Define 3 separate classes: separate classes: GSMGSM, , BatteryBattery and and DisplayDisplay..

10.10. Define several constructors for the defined Define several constructors for the defined classes that take different sets of arguments classes that take different sets of arguments (the full information for the class or part of it). (the full information for the class or part of it). The unknown data fill with The unknown data fill with nullnull..

11.11. Add a static field Add a static field NokiaN95NokiaN95 in the in the GSMGSM class to class to hold the information about Nokia N95 device.hold the information about Nokia N95 device.

Page 49: Defining classes-and-objects-1.0

Exercises (5)Exercises (5)

12.12. Add a method in the class Add a method in the class GSMGSM for displaying for displaying all information about all information about itit..

13.13. Use properties to encapsulate data inside Use properties to encapsulate data inside the the GSMGSM, , BatteryBattery and and DisplayDisplay classes.classes.

14.14. Write a class Write a class GSMGSMTestTest to test to test the functionality the functionality of the of the GSMGSM class. class.

• Create several instances of the class and Create several instances of the class and store them in an array.store them in an array.

• Display the information about the created Display the information about the created GSMGSM instances. instances.

• Display the information about the static Display the information about the static member member NokiaN95NokiaN95

Page 50: Defining classes-and-objects-1.0

Exercises (6)Exercises (6)

15.15. Create a class Create a class CallCall to hold a call performed to hold a call performed with a GSM. It should contain date, time and with a GSM. It should contain date, time and duration.duration.

16.16. Add a property Add a property CallsHistoryCallsHistory in the in the GSMGSM class class to hold a list of the performed calls.to hold a list of the performed calls.

17.17. Add a methods in the Add a methods in the GSMGSM class for adding and class for adding and deleting calls to the calls history. Add a deleting calls to the calls history. Add a method to clear the call history.method to clear the call history.

18.18. Add a method that calculates the total price of Add a method that calculates the total price of the calls in the call history. Assume the price the calls in the call history. Assume the price per minute is given as parameter.per minute is given as parameter.

Page 51: Defining classes-and-objects-1.0

Exercises (7)Exercises (7)

19.19. Write a class Write a class GSMCallHistoryTestGSMCallHistoryTest to test to test the the call history functionality of the call history functionality of the GSMGSM class. class.

• Create an instance of the Create an instance of the GSMGSM class. class.

• Add few calls.Add few calls.

• Display the information about the calls.Display the information about the calls.

• Assuming that the price per minute is 0.37 Assuming that the price per minute is 0.37 calculate and print the total price of the calls.calculate and print the total price of the calls.

• Remove the longest call from the history Remove the longest call from the history and calculate the total price again.and calculate the total price again.

• Finally clear the call history.Finally clear the call history.

Page 52: Defining classes-and-objects-1.0

Exercises (8)Exercises (8)

20.20. Define class Define class FractionFraction that holds information that holds information about fractions: numerator and denominator.about fractions: numerator and denominator.The format is "numerator/denominator". The format is "numerator/denominator".

21.21. Define static method Define static method Parse()Parse() which is trying to which is trying to parse the input string to fraction and passes the parse the input string to fraction and passes the values to a constructor.values to a constructor.

22.22. Define appropriate constructors and properties. Define appropriate constructors and properties. Define property Define property DecimalValue DecimalValue which converts which converts fraction to decimal value.fraction to decimal value.

23.23. Write a class Write a class FractionTFractionTestest to test to test the the functionality of the functionality of the FractionFraction class. Try to parse a class. Try to parse a sequence of fractions from a text file and print sequence of fractions from a text file and print their decimal values at the console. Don't forget to their decimal values at the console. Don't forget to catch possible exceptions.catch possible exceptions.

Page 53: Defining classes-and-objects-1.0

Exercises (9)Exercises (9)

24.24. We are given a library of books. Define classes We are given a library of books. Define classes for the library and the books. The library for the library and the books. The library should have name and a list of books. The should have name and a list of books. The books have title, author, publisher, year of books have title, author, publisher, year of publishing and ISBN.publishing and ISBN.

25.25. Implement methods for adding, searching Implement methods for adding, searching by title and author, displaying and deleting by title and author, displaying and deleting books.books.

26.26. Write a test class that creates a library, adds Write a test class that creates a library, adds few books to it and displays them. Find all few books to it and displays them. Find all books by Steven King and delete them. books by Steven King and delete them. Finally print again the library.Finally print again the library.