More about Java Classes Writing your own Java Classes More about constructors and creating objects.

Slides:



Advertisements
Similar presentations
Objects and Classes Part II
Advertisements

1 Classes and Objects in Java Basics of Classes in Java.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Classes and Objects: Recap A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
Road Map Introduction to object oriented programming. Classes
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Objects Interaction and Source Code Week 2. OBJECT ORIENTATION BASICS REVIEW.
Classes and Objects  A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
Object Oriented Software Development
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
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.
1 Classes and Objects in C++ 2 Introduction Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Learners Support Publications Classes and Objects.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Programs and Classes A program is made up from classes Classes may be grouped into packages A class has two parts static parts exist independently Non-static.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
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.
CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2.
M1G Introduction to Programming 2 5. Completing the program.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
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.
Learners Support Publications Constructors and Destructors.
 An object is basically anything in the world that can be created and manipulated by a program.  Examples: dog, school, person, password, bank account,
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Constructors and Destructors
Classes and Objects Introduced
Static data members Constructors and Destructors
Introduction to C++ Systems Programming.
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Classes and Objects in Java
Road Map Introduction to object oriented programming. Classes
This pointer, Dynamic memory allocation, Constructors and Destructor
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Object Oriented Programming in java
Constructors and Destructors
Classes and Objects.
CISC/CMPE320 - Prof. McLeod
Programs and Classes A program is made up from classes
Object Oriented Programming in java
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming Language
In this class, we will cover:
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
SPL – PS3 C++ Classes.
Presentation transcript:

More about Java Classes Writing your own Java Classes More about constructors and creating objects

Java Objects We can define our own types using the Java keyword class Your understanding and use of Classes/objects is fundamental to getting to grips with Java It is also the biggest climb on the learning curve - so be patient

What are Java Classes? Classes are templates They encapsulate data (variables) and behaviour (methods) Variables can either be primitive (int, char etc) or reference types (String etc)

Classes and Objects – there is a difference An object is an occurrence (or instance) of a Class The Class describes the blueprint or template An object is made from a class For an Employee class, each employee would be an object with the data and method structure of the class Although the structure is the same for all objects built from this class, the values held within the data can be different

How to Create objects from a class? The new keyword is used to create an instance of a class - an object reference Employee JonWestlake = new Employee( ); new is the ONLY way to create objects** See examples Employee1.java - a single class with one object Employee2.java - a single class with two objects Employee3.java - a single class with many objects

What does that new statement mean? Employee JonWestlake = new Employee( ); Declares a “reference variable” of type Employee So JonWestlake does have a memory location but no “pointer” to an object yet - essentially a null object

Breakdown of new statement Right hand side = new Employee( ); Creates an object of the Employee class We could have done the statements in two stages; Employee JonWestlake; JonWestlake = new Employee( );

What is an object reference? Think of a reference as a name for an object - JonWestlake is the name of a an Employee object Employee JonWestlake = new Employee( ); reference names can be meaningful as in this case or as we can see with the Employee application

Object references It is legal for two references (or more) to refer to the same object e.g. in the Employee example we might wish to refer to the object via some initials as well Employee JonWestlake = new Employee( ); Employee jcw = JonWestlake; jcw refers to the same Employee as JonWestlake

What does new do? - memory new takes the memory it needs to create an object from a special memory pool that Java controls automatically, called the heap All class objects in Java come from the heap Java allocates enough memory to hold the object Java allocates memory for objects when the object is created, not at application start up

What does new do? - constructor Java initialises any instance variables to default values - default constructor Java makes calls to any constructors that exist for that class So, what is a constructor?

Content of Constructors Constructors are a “special” method used to initialise an object created for a class The name is the same as the class, so starts with a capital letter Constructor can do anything a normal method can do** No return type - not even void The constructor does not contain a return statement

Content of Constructor Like any method a constructor can include arguments. These arguments indicate to the constructor how to set up the initial values for the data fields of an object See Employee2 for example

What happens if we don’t use a Constructor? Every class has a single default constructor with no parameters The default constructor takes no arguments and does nothing other than initialize all object variables to their zero or null state As soon as the developer defines a constructor then the default constructor is no longer used

What should a Constructor do? Creating objects to a valid starting state according to content of the constructor and arguments passed into the constructor they are usually used to simply initialize variables within the object to some starting value or they could be used to add objects to a linked list or increment an object count…

What should the Constructor do? We advise you not to place instance style functionality within the constructor Use the constructor to initialize an instance - keeps it simple and maintainable!

Overloading the Constructor A class is free to have more than one constructor The constructors must have different argument signatures Often one “root” constructor has all the program logic for construction Other constructors set a few defaults and then call the root constructor

Example Overloaded Constructor Item(String itemDesc) {Item(itemDesc, 0); } Item(String itemDesc, int itemWght) {description = itemDesc; weight = itemWght; }

new operator for Item class The first example of the constructor sets the item weight to 0 and passes this information on to the full constructor Item defaultItem = new Item(“General Stock”); Alternatively, you could call the second constructor directly Item specifyItem = new Item(“Widgets”, 50);

Overloading Constructors - Tips Place all the initialisation code in a root constructor Root constructor is usually the constructor with the most parameters define “convenience” constructors with fewer parameters - these constructors call the root constructor using default values for the parameters which the user has not provided See Employee5.java example

Using a test to drive the choice of constructor We can ask the user something Based on the user input, we can test the input and select the constructor appropriate to the input See VideoEx1.java or Employee5.java

Invoking one Constructor from another One constructor can invoke another constructor of the same class using the this keyword this - a special (pseudo) variable pseudo means the value is changed by the system not the developer a reference to the object within which a constructor is executing useful as it enables messages to “this” the current object to be performed - see VideoEx2.java

Running the Constructor Constructors do not have an explicit keyword to mark them as such and they cannot be called like a normal method see Employee1, Employee2 and Employee3

Where to position the constructor? Position the constructor either before the main method (if there is one for the class) or after the main method see the examples Each constructor is defined separately i.e. not nested

Constructor access modifiers The access modifiers are exactly the same as for classes - public or nothing** Modifier must be public if classes outside of the current package need to be able to use the object being defined - design issue if public is not used then constructor is only available within the package to which the class belongs - for our work this is usually the case

Destructors! There is NO destructor in Java In C++ a destructor is used to return memory to heap of available memory Java manages memory automatically via the constructor and automatically returns memory when objects are abandoned

Summary We have looked further at classes We have investigated the role of the constructor Practical – get the examples running and write your own versions!