1 / 46

Classes and Instances

Classes and Instances. Introduction Classes, Objects, Methods and Instance Variables Declaring a Class with a Method and Instantiating an Object of a Class Declaring a Method with a Parameter Instance Variables, set Methods and get Methods Primitive Types vs. Reference Types

hiroko
Download Presentation

Classes and Instances

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Classes and Instances

  2. Introduction • Classes, Objects, Methods and Instance Variables • Declaring a Class with a Method and Instantiating an Object of a Class • Declaring a Method with a Parameter • Instance Variables, set Methods and get Methods • Primitive Types vs. Reference Types • Initializing Objects with Constructors

  3. Class • There are many objects of the same type, customers, cars, bicycles… • The same kinds of objects are grouped into classes • A class defines the fields and the methods that each object of that type will have • a class is a blueprint or template • E.g. Customer class defines all the fields and the method implementations that each customer will have

  4. Instances • Each object of a particular type is an instance of the class • your bike is an instance of the class Bicycle • Joe Bloggs is an instance of the class Customer • All instance objects share the same blueprint i.e. class • Each instance object of a class is separate, and individual • each has the same structure and behaviour • each has different actual values • There are many instance objects for each class

  5. Class vs Instance Objects Class Instance 1 Instance 4 Instance 2 Instance 3 All instances of the same class

  6. Class vs Instance Objects Student Mary Black Sean Smith Niamh Connor Eoin Murphy All instances of the same class

  7. Declaring a Class with a Method and Instantiating an Object of a Class • keyword public is an access modifier • Class declarations include: • Access modifier • Keyword class • Pair of left and right braces

  8. classes are defined in the following way: class MyClass { //field, constructor, and method declarations }

  9. Class Definition class Student { // fields String name; int studentNo; String course; //related to other Objects // methods void register(){ ... } void completeYear(int year){ ... } void graduate(){ ... }}

  10. Class Members • There are two types of members of a class • class members • instance members • Class members are associated with the class object • exist once, a single copy • Instance members are associated with each instance object • multiple copies of an instance member exists, one copy in each instance object • Note: object members = object fields + object methods

  11. Class vs Instance Members Class: StudentReg Fee: E600 changeFee(double) Mary Black0345678FT211 register()completeYear(int)graduate() Sean Smith05076543FT228 Niamh Connor04565656FT211 register()completeYear(graduate() Eoin Murphy05234567FT228 register()completeYear(int)graduate() register()completeYear(int)graduate()

  12. Class vs Instance members class Student { // instance fields String name; int studentNo; String course; // class fields static double regFee = 600; // class methods static void changeFee(double fee){ ... } // instance methods void register(){ ... } } class members declared using keyword static

  13. Class members • Classfields • a class field has the same value for all instances of the object • a class field declared with a final modifier is a constant public static final double PI=3.14159; • Class methods • a class method cannot use any instance members (fields or methods)

  14. Declaring a Class with a Method and Instantiating an Object of a Class • Method declarations • Keyword public indicates method is available to public • Keyword void indicates no return type • Access modifier, return type, name of method and parentheses comprise method header

  15. class type constructor instance objectvariable name Creating Instance Objects- new keyword • Instance objects are created from the class definition • To create instance objects need a special type of method called a constructor • Instance objects are created using the keyword new • E.g. Student me = new Student();

  16. Constructor • The constructor • has the same name as the class(watch case sensitivity!) • allocates enough space for an instance object of the class specified • does not specify a return type • should initialise all instance fields

  17. Constructor class Student { // fields String name; int studentNo; String course;// constructor Student (String n, int s, String c){ name=n; studentNo=s; course=c; } // methods ...}

  18. Program Structure • An OO program is a collection of objects interacting with each other • There are three types of classes • business class – for objects which represent persistent data in the system, • interface class – for objects that represents an interface (e.g. screen, file reader, etc…) • control class – for objects that control the flow of interaction • All programs need a program control class that starts the program running (i.e. has the main method)

  19. Example • One technique is to • instantiate the program control class in the main method • include the work of the program in the program control class constructor • Could include main work of program in main but cannot access instance members…

  20. Simple Program Simple Program class Classid{ // constructorClassid(){ Data and Control } // main method to start execution public static void main (String[] args) { new Classid();// instantiating } } The Java system calls the main method which instantiates the program via a new on the constructor for Classid. Execution of the program proceeds from the constructor and ends with the last statement in sequence has been reached.

  21. Example: Creating Objects program control class public class HelloWorld1{ // constructorHelloWorld1(){ System.out.println("Hello World yet again..."); } // main method to start executionpublic static void main (String[] args) { new HelloWorld1();// instantiating } }

  22. Another Example • // Class declaration with one method. • public class GradeBook • { • public GradeBook(){ • System.out.println( "Welcome to the Grade Book!" ); • } • // display a welcome message to the GradeBook user • public void displayMessage() • { • System.out.println( "Welcome to the Grade Book!" ); • } // end method displayMessage • } // end class GradeBook

  23. This is called from this class • // Create a GradeBook object and call its displayMessage method. • public class GradeBookTest • { • GradeBookTest() • { • // create a GradeBook object and assign it to myGradeBook • // call the constructor for the class GradeBook • GradeBook myGradeBook = new GradeBook(); • // call myGradeBook's displayMessage method • myGradeBook.displayMessage(); • } // end main • public static void main (String[] args) { • // Start the program running from its constructor • new GradeBookTest();} • } // end class GradeBookTest

  24. Consider what is happening • We are creating an instance of GradeBook from this class GradeBookTest • See the line • GradeBook myGradeBook = new GradeBook(); • We then call on the line • myGradeBook.displayMessage(); • This calls the displayMessage method from the GradeBook class

  25. Next Lecture • How do we implement all this

  26. Some Background ActivitiesAround Classes • We discussed some classes and programs that called them. • For example we had the GradeBook and Grade Book Test Classes

  27. Another Example • // Class declaration with one method. • public class GradeBook • { • // display a welcome message to the GradeBook user • public void displayMessage() • { • System.out.println( "Welcome to the Grade Book!" ); • } // end method displayMessage • } // end class GradeBook

  28. This is called from this class • // Create a GradeBook object and call its displayMessage method. • public class GradeBookTest • { • GradeBookTest() • { • // create a GradeBook object and assign it to myGradeBook • // call the constructor for the class GradeBook • GradeBook myGradeBook = new GradeBook(); • // call myGradeBook's displayMessage method • myGradeBook.displayMessage(); • } // end main • public static void main (String[] args) { • // Start the program running from its constructor • new GradeBookTest();} • } // end class GradeBookTest

  29. Consider what is happening • We are creating an instance of GradeBook from this class GradeBookTest • See the line • GradeBook myGradeBook = new GradeBook(); • We then call on the line • myGradeBook.displayMessage(); • This calls the displayMessage method from the GradeBook class

  30. Next • How do we implement all this • We need to do this by linking all the classes together. • One way of doing this is with the –classpath qualifier at compilation time using the javac command • We have already seen this at run time with the java command. But we can use the same idea at compilation time • This will tell the compiler where to find classes. • See the following dialogue

  31. Directory mnemonics • In Dos the directory hierarchy uses some short cuts • \ refers to the root directory • So if we type cd \ • We will be returned to the root directory • The parent directory of any directory is indicated by .. • So if we were in C:\johns\java\progs and we typed cd .. • We will be returned to C:\johns\java

  32. Directory mnemonics . notation • The current directory is indicated by . • So when we use . We are referring to the current directory • So javac –classpath . GradeBook will look for classes in the current directory. So the java classes used must be there.

  33. Consider the following two Classes • Book • And Bookstore1 due to June Barrett • Their Code is

  34. Book.java • public class Book { • // Declare instance fields • String name; • int price; • // The constructor initialises the instance fields • Book (String n, int p) { • name = n; • price = p; • } • // a method to output the object details • void write() { • System.out.println(name + " for £" +price); • } • }

  35. BookStore1.java • public class BookStore1 { • /* Illustrating the basic structure of an object oriented program */ • // Declare three object variables representing type of • // goods sold in the store • Book TextBook, Novel,ShortStory;

  36. BookStore1.java continued • // The constructor for the program is • // where the initial work gets done • BookStore1 () { • // Create three objects with different initial values • TextBook = new Book("Java Programming", 6); • Novel = new Book("The Unsung Hero", 30); • ShortStory = new Book("Stories for 5 year olds", 80); • // Print out a header • System.out.println("The Book Store sells\n"); • // Print the values contained in each of the objects • TextBook.write(); • Novel.write(); • ShortStory.write(); • }

  37. And Finally • // The program control class must have a main method • public static void main (String[] args) { • // Start the program running from its constructor • new BookStore1 (); • } • }

  38. The Constructor BookStore1 • We see from the code that the constructor BookStore1() make three instance of the class Book, namely TextBook,Novel and ShortStory • It then calls on the Book write method to display details about the book.

  39. Next How do we compile these • Firstly Book.java and BookStore1.java must be in the same directory

  40. From a Directory Listing • We see that they are both in the c:\ directory • Next we compile and run the classes using the • Javac and Java commands with • –classpath .

  41. From this screen we see • That the class correctly executes the specific objects.

  42. Some Dos issues • The javac command is in the jdk bin subdirectory and I am fed up typing out • C:\program files\java\jdk1.5.0_16\bin\javac • Or whatever in order to use the command

  43. Solution set a dos path • set path=c:\program files\java\jdk1.5.0_16\bin • This is the path on my computer for Java jdk version 5 • NBNBNBYou need whatever path there is to the bin directory in java jdk where javac is stored ON YOUR COMPUTER!!!!! • Then the O/S will try this path when you invoke javac

More Related