Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Fields, Constructors, Methods
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Written by: Dr. JJ Shepherd
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Lecture 2: Object Oriented Programming I
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
Road Map Introduction to object oriented programming. Classes
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
JVM-1 Java Virtual Machine Reading Assignment: Chapter 1: All Chapter 3: Sections.
Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
1 Classes and Objects Overview l Classes and Objects l Constructors l Implicit Constructors l Overloading methods this keyword l public, private and protected.
Unit 061 Java Virtual Machine (JVM) What is Java Virtual Machine? The Class Loader Subsystem Linking oVerification oPreparation oResolution Class Initialization.
1 Further OO Concepts II – Java Program at run-time Overview l Steps in Executing a Java Program. l Loading l Linking l Initialization l Creation of Objects.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Chapter 5 Introduction to Defining Classes
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Classes Modeling the Object. Objects model the world Classes are programmer defined types that model the parts of a system Class serve as blueprints for.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
More Object Concepts— Farrell, Chapter 4 Dr. Burns.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Developed at Sun Microsystems in 1991 James Gosling, initially named “OAK” Formally announced java in 1995 Object oriented and cant write procedural.
Interfaces and Inner Classes
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java Programming, Second Edition Chapter Three Using Methods, Classes, and Objects.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Topics Instance variables, set and get methods Encapsulation
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming Language Lecture27- An Introduction.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Classes (Part 1) Lecture 3
3 Introduction to Classes and Objects.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java Programming Language
Packages and Interfaces
Object Oriented Programming in java
Java Programming Language
CSG2H3 Object Oriented Programming
Presentation transcript:

Initialization George Blank Subba Reddy Daka

Importance of Initialization Java classes are initialized and have predictable default values. These values are stored in memory allocated on the heap when the class is instantiatedJava classes are initialized and have predictable default values. These values are stored in memory allocated on the heap when the class is instantiated Uninitialized data is a source of bugs!Uninitialized data is a source of bugs!

Types of Initialization Instance Initializers (also called instance initialization blocks). Instance variable initializers. Constructors. You should ensure that any of the three types produce a valid state for newly created objects.

Default Initial Values This table shows the default initial values for each of the variable types. TypeDefault Value booleanFalse byte(byte) 0 short(short)0 int0 long0L char\u 000 float0.0f double0.0d object informationnull

If you don't explicitly initialize an instance variable, that variable will retain its default initial value when new returns its object reference. // In source packet in file // init/ex1/CoffeeCup.java // This class has no constructors or initializers class CoffeeCup { private int innerCoffee; //... } As a result, when the reference to a new CoffeeCup object is first returned by new, the innerCoffee field will be its default initial value. Because innerCoffee is an int, its default initial value is zero.

Constructors Constructor basics In the source file, a constructor looks like a method declaration in which the method has the same name as the class but has no return type. For example, here is a constructor declaration for class CoffeeCup: // In source packet in file init/ex2/CoffeeCup.java class CoffeeCup { // Constructor looks like a method declaration // minus the return type public CoffeeCup() { // Body of constructor } //... }

When you instantiate an object with new, you must specify a constructor. For example, given the CoffeeCup class above that has two constructors, you could instantiate it in either of these two ways: // In source packet in file init/ex3/Example3.java class Example3 { public static void main(String[] args) { // Create an empty cup CoffeeCup cup1 = new CoffeeCup(); // Create a cup with 355 ml of coffee in it CoffeeCup cup2 = new CoffeeCup(355); } // Above requires constructor shown later } Constructors are not methods

Default constructors If you declare a class with no constructors, the compiler will automatically create a default constructor for the class. A default constructor takes no parameters. The compiler gives default constructors the same access level as their class.

Instance initialization methods When you compile a class, the Java compiler creates an instance initialization method for each constructor you declare in the source code of the class. class CoffeeCup { public CoffeeCup() { //... } public CoffeeCup(int amount) { //... } //... }

The compiler would generate the following two instance initialization methods in the class file for class CoffeeCup, one for each constructor in the source file: // In binary form in file init/ex8/CoffeeCup.class: public void (CoffeeCup this) {...} public void (CoffeeCup this, int amount) {...} Instance initialization

In a constructor, you have the freedom to write as much code as needed to calculate an initial value. In an instance variable initializer, you have only an equals sign and one expression. // In source packet in file init/ex9/CoffeeCup.java class CoffeeCup { private int innerCoffee; public CoffeeCup() { innerCoffee = 355; } //... } Instance Variable Initializers

Explanation // In source packet in file init/ex10/CoffeeCup.java class CoffeeCup { private int innerCoffee = 355; // "= 355" is an initializer // no constructor here //... } The right-hand side of the equals sign in an initializer can be any expression that evaluates to the type of the instance variable.

Instance initializers An instance initializer, also called an instance initialization block is shown here with the CoffeeCup class innerCoffee variable initialized by an instance initializer: // In source packet in file init/ex19/CoffeeCup.java class CoffeeCup { private int innerCoffee; // The following block is an instance initializer { innerCoffee = 355; } // no constructor here //... } This manner of initializing innerCoffee yields the same result as the previous two examples: innerCoffee is initialized to 355.

Initializers can't make forward references When you write an initializer (either an instance variable initializer or instance initializer), you must be sure not to refer to any instance variables declared textually after the variable being initialized. In other words, you can't make a forward reference from an initializer.

Initialization and inheritance When an object is initialized, all the instance variables defined in the object's class must be set to proper initial values.

Instance data of objects Every object, except class Object itself, has at least one superclass. When an object is created, the Java virtual machine allocates enough space for all the object's instance variables, which include all fields defined in the object's class and in all its superclasses. For example, consider the following classes:virtual machine

// Declared in file Object.java (not In source packet) package java.lang; public class Object { // Has no fields // Has several methods, not shown... } // In source packet in file init/ex14/Liquid.java class Liquid { // Has two fields: private int mlVolume; private float temperature; // in Celsius // Has several methods, not shown... } // In source packet in file init/ex14/Coffee.java class Coffee extends Liquid { // Has two fields: private boolean swirling; private boolean clockwise; // Has several methods, not shown... }java

Here you can see the data that must be allocated on the heap for a Coffee object. The part of the heap that is occupied by the instance data for the Coffee object is shown in the cyan color. Keep in mind that the actual manner of representing objects on the heap is an implementation detail of each particular Java virtual machine.

Order of initialization In Java, the fields of an object are initialized starting with the fields declared in the base class and ending with the fields declared in the object's class. For a CoffeeCup object with the inheritance path shown in Figure 1, the order of initialization of fields would be: Object's fields (this will be quick, because there are none) Liquid's fields (mlVolume and temperature)

Coffee's fields (swirling and clockwise) This base-class-first order aims to prevent fields from being used before they are initialized to their proper (not default) values.

Example: Constructors in java.lang.String String() String(byte[]) String(byte[], int) String(byte[], int, int) String(byte[], int, int, int) String(byte[], int, int, String) String(byte[], String) String(char[]) String(char[], int, int) String(String) String(StringBuffer)

Private and Protected Constructors Most constructors are public. There are some circumstances in which a private or protected constructor is used. For example, a private constructor is appropriate with a class using only static utility methods or constants, type safe enumerations, or a singleton class. Protected constructors are used to prevent instantiation outside the package.

References THE JAVA HANDBOOK- PatrickNaughton