Classes and Objects Defining Classes and Objects
Contents Defining simple classes Using classes Constructors Properties Static Members
Defining  S imple  C lasses
What a Class Should Contain? Mechanism to create new object of the current type (for non-abstract classes) Information about base classes Properties that are relevant to the problem Operations that can be used (methods)
Defining Classes Simple class definition: public class Cat extends Animal { private String name; public Cat(String name) { this.name = name; } public void SayMiau() { System.out.printf("Cat %s said: Miauuuuuu!", name); } } Class Field Constructor Method
Elements of Class Definitions Class declaration Can be followed by inherited class or implemented interfaces Constructors (static or instance) Fields (static or instance) Properties (static or instance) Methods (static or instance) Events (static or instance)
Defining  S imple  C lasses Examples
Task: Define a Class You should define a simple class that represents a cat The cat should have a name You should be able to view and change the name of the cat The cat should be able to mew If there is no name assigned to the cat it should be named “ Nastradin ”
Defining Simple Class Our pet as a class: public class Cat { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } // (The example continues on the next slide) Class definition Field definition Property getter Property setter
Defining Simple Class (2) public Cat() { this.name = "Nastradin"; } public Cat(String name) { this.name = name; } public void  s ayMiau() { System.out.printf( "Cat %s said: Miauuuuuu!%n", name); } }  Method definition Constructor definition Constructor definition
Using  C lasses
What to Do With Classes? Create new instance Set / Get properties of the class Execute methods Handle events Create new classes derived from existing ones
How to Use Classes? Create instance Initialize fields Manipulate instance Set / Get properties Execute methods Handle events Release occupied resources – it’s done in most cases automatically
Using  C lasses Example
Task: Cat Meeting Create 3 cats First should be named “Garfield”, second – “Tom” and last – no name Add all cats in array Iterate through the array and make every cat to mew NOTE: Use Cat class from the previous example!
Manipulating Class Instances public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Write first cat name: "); String firstCatName = input.nextLine(); // Assign cat name with a constructor Cat firstCat = new Cat(firstCatName); System.out.println("Write second cat name: "); Cat secondCat = new Cat(); // Assign cat name with a property secondCat.setName(input.nextLine()); // Create a cat with a default name Cat thirdCat = new Cat(); Sample task solution: // (The example continues on the next slide)
Manipulating Class Instances (2) Cat[] cats = new Cat[] {   firstCat,    secondCat,    thirdCat }; for(Cat cat  :  cats)   {  cat.SayMiau();  } }
Using  C lasses  in Java Live Demo
Constructors Defining and Using Constructors in the Classes
What is a Constructor? Creates a new instance of an object Executes automatically when we create new objects Must initialize fields of the instance
Defining Constructors Constructor has the same name as the class Has no return type Can be private, protected, public or  default Can have parameters public class Point   { private int xCoord; private int yCoord; public Point()  {  //  S imple default constructor xCoord = 0; yCoord = 0; } // More code ... }
Constructors Examples
Defining Constructors public class Person { private String name; private int age; // Default constructor public Person() { this.name = null; this.age = 0; } // Constructor with parameters public Person(String name, int age) { this.name = name; this.age = age; } //More code ...  }
Indirect Constructors NOTE: Be careful when using inline initialization ! p ublic class ClockAlarm { private int hours = 0; // Inline field initializatio n private int minutes = 0; // Inline field initialization // Default constructor public ClockAlarm() { } // Constructor with parameters p ublic ClockAlarm(int hours, int minutes) { this.hours = hours; this.minutes = minutes; } // More code ... }
Advanced Techniques Reusing constructors public class Point { // Definition of fields (member variables) private int xCoord; private int yCoord; private String name; // The default constructor calls the other constructor public Point() { this(0, 0); } // Constructor to parameters public Point(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; name = String.format("(%d,%d)", this.xCoord,      this.yCoord); } // More code ... }
Constructors Live Demo
Properties Defining and Using Properties
What is a Property Properties are not exactly part of Java. They are good practice and important part of OOP Expose object's data to the outside world Control the way data is manipulated Define if data can be: Read Written Read and written Gives good level of abstraction
Defining Properties Properties is defined with: Field with  private  access modifier Getter  and/or  Setter  method getter  – method returning the value of the field setter  – method setting the value of the field public class Point   { private int xCoord; public int getXCoord() { return xCoord; } public void setXCoord(int coord) { xCoord = coord; } }
Properties Examples
Capsulate Fields public class Point  { private  int xCoord; private  int yCoord; // constructing code ... public int getXCoord() { return this.xCoord; } public void setXCoord(int value) { this.xCoord = value; } public int get Y Coord() { return this. y Coord; } public void set Y Coord(int value) { this. y Coord = value; } // More code ... }  Fields are encapsulated as private members Getters and Setter allow controlled access to the private fields
Dynamic Properties You can create properties that are not bound to a class field public class Rectangle { private float width; private float height; public Rectangle(float width, float height) { // Some initialization code } public float getArea() { return width * height; } }
Properties Live Demo
Static Members Static vs. Instance Fields, Methods and Properties
What is  static ? Static items are associated with a type rather than with an instance Can be used with Fields Methods Constructor
Static vs. Non-Static Static : Associated with a type, not with an instance Non-Static : the opposite Static : Initialized when type is used for the first time (Pay attention!) Non-Static : Initialized when the constructor is called
Static Members Examples
Static Members – Example public class Sequence { private static int currentValue = 0; private Sequence() { // Deny instantiation of this class } public static int nextValue() { currentValue++; return currentValue; } } public class TestSequence { public static void main(String[] args) { System.out.printf("Sequence[1..3]: %d, %d, %d ",  Sequence.nextValue(), Sequence.nextValue(),  Sequence.nextValue()); } }
Static Members Live Demo
Creating Static Methods public class Fraction   { private int numerator; private int denominator; public Fraction(int num, int denom)   { this.numerator = num; this.denominator = denom; } public  static  Fraction Parse( S tring val)   { S tring[] parts = val. s plit( " / " ); int num = Integer.parseInt(parts[0]); int denom = Integer.parseInt(parts[1]); Fraction result = new Fraction(num, denom); return result; } }
Calling Static Methods Parsing custom type from string public static void main(String[] args) { String fractStr = "2/3"; try { fraction =  Fraction.Parse (fractStr); System.out.println("fraction = " + fraction); } catch (Exception ex) { System.out.println("Can not parse the fraction."); } }
Parsing Fractions Live Demo
Summary Classes define specific structure for  the objects Objects are class' instances and use  this structure Constructors initialize object state Properties encapsulate fields Static methods are associated with a type Non-static – with and instance (object)
Lecture Topic Questions?
Exercises Define class  Student  that holds information about students: full name, course, specialty, university, email, phone. Use enumeration for the specialties and universities. Define several constructors for the class  Student  that take different sets of arguments (the full information about the student or part of it). The unknown data fill with  null  or  0 . Add a static field in the  Student  class to hold the total number of instances ever created. To keep this value current, modify the constructors as necessary.
Exercises (2) Add a method in the class  Student  for displaying all information about the student. Use properties to encapsulate data inside the  Student  class. Write a class  StudentTest  to test  the functionality of the  Student  class: Create several students and display all information about them. Add a static constructor in the  StudentTest  class that creates several instances of the class  Student  and holds them in static variables. Create a static property to access them. Write a test program to print them.
Exercises (3) We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name. Disciplines have name, number of lectures and number of exercises. Both teachers and students are persons. Your task is to model the school with Java classes. You need to define the classes along with their fields, properties and constructors.
Exercises (4) Define a class that holds information about  mobile phone device: model, manufacturer, price, owner, battery characteristics (model, hours idle and hours talk) and display characteristics (size and colors). Define 3 separate classes:  GSM ,  Battery  and  Display . Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). The unknown data fill with  null . Add a static field  NokiaN95  in the  GSM  class to hold the information about Nokia N95 device.
Exercises (5) Add a method in the class  GSM  for displaying all information about  it . Use properties to encapsulate data inside  the  GSM ,  Battery  and  Display   classes. Write a class  GSM Test  to test  the functionality of the  GSM  class. Create several instances of the class and store them in an array. Display the information about the created  GSM  instances. Display the information about the static member  NokiaN95
Exercises (6) Create a class  Call  to hold a call performed with a GSM. It should contain date, time and duration. Add a property  CallsHistory  in the  GSM  class to hold a list of the performed calls. Add a methods in the  GSM  class for adding and deleting calls to the calls history. Add a method to clear the call history. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is given as parameter.
Exercises (7) Write a class  GSMCallHistoryTest  to test  the call history functionality of the  GSM  class. Create an instance of the  GSM  class. Add few calls. Display the information about the calls. Assuming that the price per minute is 0.37 calculate and print the total price of the calls. Remove the longest call from the history  and calculate the total price again. Finally clear the call history.
Exercises (8) Define class  Fraction  that holds information about fractions: numerator and denominator. The format is "numerator/denominator".  Define static method  Parse()  which is trying to parse the input string to fraction and passes the values to a constructor. Define appropriate constructors and properties. Define property  DecimalValue  which converts fraction to decimal value. Write a class  FractionT est  to test  the functionality of the  Fraction  class. Try to parse a sequence of fractions from a text file and print their decimal values at the console. Don't forget to catch possible exceptions.
Exercises (9) We are given a library of books. Define classes for the library and the books. The library should have name and a list of books. The books have title, author, publisher, year of publishing and ISBN. Implement methods for adding, searching  by title and author, displaying and deleting books. Write a test class that creates a library, adds few books to it and displays them. Find all books by Steven King and delete them.  Finally print again the library.

Defining classes-and-objects-1.0

  • 1.
    Classes and ObjectsDefining Classes and Objects
  • 2.
    Contents Defining simpleclasses Using classes Constructors Properties Static Members
  • 3.
    Defining Simple C lasses
  • 4.
    What a ClassShould Contain? Mechanism to create new object of the current type (for non-abstract classes) Information about base classes Properties that are relevant to the problem Operations that can be used (methods)
  • 5.
    Defining Classes Simpleclass definition: public class Cat extends Animal { private String name; public Cat(String name) { this.name = name; } public void SayMiau() { System.out.printf("Cat %s said: Miauuuuuu!", name); } } Class Field Constructor Method
  • 6.
    Elements of ClassDefinitions Class declaration Can be followed by inherited class or implemented interfaces Constructors (static or instance) Fields (static or instance) Properties (static or instance) Methods (static or instance) Events (static or instance)
  • 7.
    Defining Simple C lasses Examples
  • 8.
    Task: Define aClass You should define a simple class that represents a cat The cat should have a name You should be able to view and change the name of the cat The cat should be able to mew If there is no name assigned to the cat it should be named “ Nastradin ”
  • 9.
    Defining Simple ClassOur pet as a class: public class Cat { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } // (The example continues on the next slide) Class definition Field definition Property getter Property setter
  • 10.
    Defining Simple Class(2) public Cat() { this.name = "Nastradin"; } public Cat(String name) { this.name = name; } public void s ayMiau() { System.out.printf( "Cat %s said: Miauuuuuu!%n", name); } } Method definition Constructor definition Constructor definition
  • 11.
    Using Classes
  • 12.
    What to DoWith Classes? Create new instance Set / Get properties of the class Execute methods Handle events Create new classes derived from existing ones
  • 13.
    How to UseClasses? Create instance Initialize fields Manipulate instance Set / Get properties Execute methods Handle events Release occupied resources – it’s done in most cases automatically
  • 14.
    Using Classes Example
  • 15.
    Task: Cat MeetingCreate 3 cats First should be named “Garfield”, second – “Tom” and last – no name Add all cats in array Iterate through the array and make every cat to mew NOTE: Use Cat class from the previous example!
  • 16.
    Manipulating Class Instancespublic static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Write first cat name: "); String firstCatName = input.nextLine(); // Assign cat name with a constructor Cat firstCat = new Cat(firstCatName); System.out.println("Write second cat name: "); Cat secondCat = new Cat(); // Assign cat name with a property secondCat.setName(input.nextLine()); // Create a cat with a default name Cat thirdCat = new Cat(); Sample task solution: // (The example continues on the next slide)
  • 17.
    Manipulating Class Instances(2) Cat[] cats = new Cat[] { firstCat, secondCat, thirdCat }; for(Cat cat : cats) { cat.SayMiau(); } }
  • 18.
    Using Classes in Java Live Demo
  • 19.
    Constructors Defining andUsing Constructors in the Classes
  • 20.
    What is aConstructor? Creates a new instance of an object Executes automatically when we create new objects Must initialize fields of the instance
  • 21.
    Defining Constructors Constructorhas the same name as the class Has no return type Can be private, protected, public or default Can have parameters public class Point { private int xCoord; private int yCoord; public Point() { // S imple default constructor xCoord = 0; yCoord = 0; } // More code ... }
  • 22.
  • 23.
    Defining Constructors publicclass Person { private String name; private int age; // Default constructor public Person() { this.name = null; this.age = 0; } // Constructor with parameters public Person(String name, int age) { this.name = name; this.age = age; } //More code ... }
  • 24.
    Indirect Constructors NOTE:Be careful when using inline initialization ! p ublic class ClockAlarm { private int hours = 0; // Inline field initializatio n private int minutes = 0; // Inline field initialization // Default constructor public ClockAlarm() { } // Constructor with parameters p ublic ClockAlarm(int hours, int minutes) { this.hours = hours; this.minutes = minutes; } // More code ... }
  • 25.
    Advanced Techniques Reusingconstructors public class Point { // Definition of fields (member variables) private int xCoord; private int yCoord; private String name; // The default constructor calls the other constructor public Point() { this(0, 0); } // Constructor to parameters public Point(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; name = String.format("(%d,%d)", this.xCoord, this.yCoord); } // More code ... }
  • 26.
  • 27.
    Properties Defining andUsing Properties
  • 28.
    What is aProperty Properties are not exactly part of Java. They are good practice and important part of OOP Expose object's data to the outside world Control the way data is manipulated Define if data can be: Read Written Read and written Gives good level of abstraction
  • 29.
    Defining Properties Propertiesis defined with: Field with private access modifier Getter and/or Setter method getter – method returning the value of the field setter – method setting the value of the field public class Point { private int xCoord; public int getXCoord() { return xCoord; } public void setXCoord(int coord) { xCoord = coord; } }
  • 30.
  • 31.
    Capsulate Fields publicclass Point { private int xCoord; private int yCoord; // constructing code ... public int getXCoord() { return this.xCoord; } public void setXCoord(int value) { this.xCoord = value; } public int get Y Coord() { return this. y Coord; } public void set Y Coord(int value) { this. y Coord = value; } // More code ... } Fields are encapsulated as private members Getters and Setter allow controlled access to the private fields
  • 32.
    Dynamic Properties Youcan create properties that are not bound to a class field public class Rectangle { private float width; private float height; public Rectangle(float width, float height) { // Some initialization code } public float getArea() { return width * height; } }
  • 33.
  • 34.
    Static Members Staticvs. Instance Fields, Methods and Properties
  • 35.
    What is static ? Static items are associated with a type rather than with an instance Can be used with Fields Methods Constructor
  • 36.
    Static vs. Non-StaticStatic : Associated with a type, not with an instance Non-Static : the opposite Static : Initialized when type is used for the first time (Pay attention!) Non-Static : Initialized when the constructor is called
  • 37.
  • 38.
    Static Members –Example public class Sequence { private static int currentValue = 0; private Sequence() { // Deny instantiation of this class } public static int nextValue() { currentValue++; return currentValue; } } public class TestSequence { public static void main(String[] args) { System.out.printf("Sequence[1..3]: %d, %d, %d ", Sequence.nextValue(), Sequence.nextValue(), Sequence.nextValue()); } }
  • 39.
  • 40.
    Creating Static Methodspublic class Fraction { private int numerator; private int denominator; public Fraction(int num, int denom) { this.numerator = num; this.denominator = denom; } public static Fraction Parse( S tring val) { S tring[] parts = val. s plit( " / " ); int num = Integer.parseInt(parts[0]); int denom = Integer.parseInt(parts[1]); Fraction result = new Fraction(num, denom); return result; } }
  • 41.
    Calling Static MethodsParsing custom type from string public static void main(String[] args) { String fractStr = "2/3"; try { fraction = Fraction.Parse (fractStr); System.out.println("fraction = " + fraction); } catch (Exception ex) { System.out.println("Can not parse the fraction."); } }
  • 42.
  • 43.
    Summary Classes definespecific structure for the objects Objects are class' instances and use this structure Constructors initialize object state Properties encapsulate fields Static methods are associated with a type Non-static – with and instance (object)
  • 44.
  • 45.
    Exercises Define class Student that holds information about students: full name, course, specialty, university, email, phone. Use enumeration for the specialties and universities. Define several constructors for the class Student that take different sets of arguments (the full information about the student or part of it). The unknown data fill with null or 0 . Add a static field in the Student class to hold the total number of instances ever created. To keep this value current, modify the constructors as necessary.
  • 46.
    Exercises (2) Adda method in the class Student for displaying all information about the student. Use properties to encapsulate data inside the Student class. Write a class StudentTest to test the functionality of the Student class: Create several students and display all information about them. Add a static constructor in the StudentTest class that creates several instances of the class Student and holds them in static variables. Create a static property to access them. Write a test program to print them.
  • 47.
    Exercises (3) Weare given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name. Disciplines have name, number of lectures and number of exercises. Both teachers and students are persons. Your task is to model the school with Java classes. You need to define the classes along with their fields, properties and constructors.
  • 48.
    Exercises (4) Definea class that holds information about mobile phone device: model, manufacturer, price, owner, battery characteristics (model, hours idle and hours talk) and display characteristics (size and colors). Define 3 separate classes: GSM , Battery and Display . Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). The unknown data fill with null . Add a static field NokiaN95 in the GSM class to hold the information about Nokia N95 device.
  • 49.
    Exercises (5) Adda method in the class GSM for displaying all information about it . Use properties to encapsulate data inside the GSM , Battery and Display classes. Write a class GSM Test to test the functionality of the GSM class. Create several instances of the class and store them in an array. Display the information about the created GSM instances. Display the information about the static member NokiaN95
  • 50.
    Exercises (6) Createa class Call to hold a call performed with a GSM. It should contain date, time and duration. Add a property CallsHistory in the GSM class to hold a list of the performed calls. Add a methods in the GSM class for adding and deleting calls to the calls history. Add a method to clear the call history. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is given as parameter.
  • 51.
    Exercises (7) Writea class GSMCallHistoryTest to test the call history functionality of the GSM class. Create an instance of the GSM class. Add few calls. Display the information about the calls. Assuming that the price per minute is 0.37 calculate and print the total price of the calls. Remove the longest call from the history and calculate the total price again. Finally clear the call history.
  • 52.
    Exercises (8) Defineclass Fraction that holds information about fractions: numerator and denominator. The format is "numerator/denominator". Define static method Parse() which is trying to parse the input string to fraction and passes the values to a constructor. Define appropriate constructors and properties. Define property DecimalValue which converts fraction to decimal value. Write a class FractionT est to test the functionality of the Fraction class. Try to parse a sequence of fractions from a text file and print their decimal values at the console. Don't forget to catch possible exceptions.
  • 53.
    Exercises (9) Weare given a library of books. Define classes for the library and the books. The library should have name and a list of books. The books have title, author, publisher, year of publishing and ISBN. Implement methods for adding, searching by title and author, displaying and deleting books. Write a test class that creates a library, adds few books to it and displays them. Find all books by Steven King and delete them. Finally print again the library.