JAVA: A Primer. By: Amrita Rajagopal

Similar documents
OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.


Data Structures using OOP C++ Lecture 3

Introduction to Object-Oriented Programming

Object-Oriented Programming Concepts

Java Professional Certificate Day 1- Bridge Session

Chapter Two Bonus Lesson: JavaDoc

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Inheritance and Interfaces

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Sri Vidya College of Engineering & Technology

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

9 Working with the Java Class Library

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Chapter 1 Getting Started

Chapter 6 Introduction to Defining Classes


Lecture 6 Introduction to Objects and Classes

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Inheritance and Polymorphism

Chapter 14 Abstract Classes and Interfaces

What is Inheritance?

Object Oriented Programming

Lecture 7: Classes and Objects CS2301

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

OBJECT ORİENTATİON ENCAPSULATİON

Short Notes of CS201

CS260 Intro to Java & Android 02.Java Technology

Data Structures (list, dictionary, tuples, sets, strings)

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Software Design and Analysis for Engineers

Packages & Random and Math Classes

C++ Important Questions with Answers

CS201 - Introduction to Programming Glossary By

Programming overview

Java OOP (SE Tutorials: Learning the Java Language Trail : Object-Oriented Programming Concepts Lesson )

Object Orientated Analysis and Design. Benjamin Kenwright

What are the characteristics of Object Oriented programming language?

2 rd class Department of Programming. OOP with Java Programming

After a lecture on cosmology and the structure of the solar system, William James was accosted by a little old lady.

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Object-Oriented Programming

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Data Abstraction. Hwansoo Han

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

Lecture 18 Tao Wang 1

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space.

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Java Libraries. Lecture 6 CGS 3416 Fall September 21, 2015

1 Shyam sir JAVA Notes


Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Java Fundamentals (II)

Introduction to Programming Using Java (98-388)

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Classes, subclasses, subtyping

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Preview from Notesale.co.uk Page 3 of 36

CS-202 Introduction to Object Oriented Programming

Unit 4 - Inheritance, Packages & Interfaces

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

COP 3330 Final Exam Review

1: Introduction to Object (1)

PROGRAMMING IN C++ COURSE CONTENT

Fundamentals of Object Oriented Programming

CSCI 253. Outline. Background. George Blankenship 1

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

7. C++ Class and Object

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

EEE-425 Programming Languages (2013) 1

Java Object Oriented Design. CSC207 Fall 2014

D Programming Language

Advantages of Object Oriented Programming :- Features of Object Oriented Programming :- Advantages Of Object Oriented Programming :

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

The Essence of OOP using Java, Nested Top-Level Classes. Preface

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

The Java Programming Language

STRUCTURING OF PROGRAM

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Oops known as object-oriented programming language system is the main feature of C# which further support the major features of oops including:

Defining Classes and Methods

Index. Course Outline. Grading Policy. Lab Time Distribution. Important Instructions

Transcription:

JAVA: A Primer By: Amrita Rajagopal 1

Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently of a browser applet--a Java program to be included in HTML pages and executed in Javaenabled browsers 2

Object Oriented Programming Key Features of OOP: 1) Data Abstraction (Encapsulation) 2) Inheritance 3) Polymorphism Discussed in future lectures 3

Key Terminology Object: An object is a software bundle of related variables and methods (same as SmallTalk) Methods (Messages): Objects interact and communicate with each other using methods. (same as SmallTalk) Class: A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind (same as SmallTalk) Interface: An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface. Inheritance: A class inherits state and behavior from its superclass (same as SmallTalk) In Java inheritance is extended to multi-level. Polymorphism: Allows improved code organization and readability as well as the creation of extensible programs that can be grown not only during the original creation of the project, but also when new features are desired. 4

Data Abstraction.or Encapsulation: The mechanism that binds together code and the data it manipulates, keeping both safe from outside interference and misuse. In Java, the basis of encapsulation is the class (same as SmallTalk) which is a logical construct; the object being its physical reality. (Discussed ahead) 5

The Class revisited A Class is a template for an object, and an object is an instance of a class. A Class describes a set of objects that have identical characteristics and behaviors, a class is really a data type For example: every bank account has a balance, every bank teller can accept a deposit, etc. At the same time, each member has its own state: each account has a different balance, each teller has a name. Thus, the tellers, customers, accounts, transactions, etc., can each be represented with a unique entity in the program. This entity is the object, and each object belongs to a particular class that defines its characteristics and behaviors 6

class classname { type instance-var1; type instance-var1; // type instance-varn; General form of a class } return-type method1( paramaters ) { //body of method } return-type method2( paramaters ) { //body of method } // return-type methodn( paramaters ) { //body of method } 7

Example: public class Car { //instance variables public char color; public int shade; //member method to change car color public void changecolor(char color, int shade) { this.color = color; this.shade = shade; System.out.print("Car color: " + this.color + ", shade: " + this.shade); } } //... 8

Hidden Implementation Implementation Hiding refers to regulating access control. Reasons for implementing access control: To keep client programmers hands off portions they shouldn t touch. To allow the library designer to change the internal workings of the class without worrying about how it will affect the client programmer. To set boundaries in a class the following Access Specifiers are used: public: The element is available to everyone. e.g.: public int a; private: The element is available only to the methods within the class where it was declared. (Same as SmallTalk) e.g.: private int a; protected: The protected keyword acts like private, with the exception that an inheriting class has access to protected members. e.g.: protected int a; 9

The this keyword this keyword is used inside methods to refer to the current object. In other words, this refers to the object that invoked the method Example: public class Car { //... } //member method to change car color public void changecolor(char color, int shade) { this.color = color; this.shade = shade; System.out.print("Car color: " + this.color + ", shade: " + this.shade); } 10

Notice in the example that the local members and method parameters have the same name. Again, the this keyword is used to distinguish between the local variables and the parameters. this.color refers to the class s instance variable color refers to the parameter. 11

Constructors Constructor functions are used to initialize objects after declaration. Constructors are used with the new operator to construct objects of a class type Constructors are class members which have the same name as the class and have no return type. The default constructor is a constructor with no arguments. A constructor with an argument list is a parameterized constructor. Examples of constructor definitions are shown on the following slide. Their usage will be explained ahead. 12

public class Car { //instance variables public char color; public int shade; //Constructor functions public Car() //default constructor { color = 'B'; shade = 1; } //parameterized constructor public Car(char color, int shade) { this.color = color; this.shade = shade; } } //... 13

Class Fundamentals Summary: A class; as discussed before, defines a new data type. This new type is used to create objects of that type. The variables defined within a class are called instance variables because each instance of the class contains its copy of these variables. Code is contained in methods. Instance variables and methods are members of the class. A class is declared by using the class keyword. Constructor functions are used to initialize objects upon declaration. 14

The Object revisited An object is a software bundle of related variables and methods. Software objects are often used to model real-world objects you find in everyday life. (Sun s definition of an object) An object is an instance of a class. An object has state, behavior and identity State internal data Behavior methods Identity each object can be uniquely distinguished from every other object 15

Creating Objects There are three aspects to object creation: Declaration declare a variable of the class type which refers to the object. Instantiation Acquire an actual copy of the object and assign it the variable. Initialization Initialize the object using constructors. (or) classname var = new classname(); classname var; var = new classname(); These two statement blocks are equivalent. First we declare the variable as a reference to an object of the particular class-type. The new keyword assigns an actual object and references it to the declared variable. The classname which follows the new keyword, actually refers to the constructor functions of the class. This part can include parameters if there exists a constructor function which requires parameters. 16

Examples: Consider the class Car again for the following declarations. Car c1 = new Car(); (or) Car c1; c1 = new Car(); Both object declarations are equivalent. They call class Car s default constructor. Therefore, the values of c1 s instance variables are: c1.color = B, c1.shade = 1. Car c1 = new Car('R', 2); (or) Car c1; c1 = new Car('R', 2); In this case, the objects are initialized using the parameterized constructor. So the instance variable values for c1 are: c1.color = R, c1.shade = 2. 17

The new keyword Consider the following segment: Car c1 = new Car(); The new operator dynamically allocates memory for an object and returns a reference to it. This reference gives the memory address of the object which is in turn stored in the variable. In the above case, new assigns memory for an object of type Car and returns the reference which is stored in variable c1. 18

Object References Lets refer back to class Car. Consider the following statements: Car c1 = new Car( ); Car c2; c2 = c1; Here c1 and c2 do not refer to separate objects. c1 and c2 actually refer to the same object. There is no allocation of new memory. But, though c1 and c2 refer to the same object, they are not linked in any way. c1 = null; c1 becomes null but c2 still points to the original object. 19

Thinking in JAVA Before we start writing JAVA programs lets go over some features of object oriented programming required to write efficient applications. SmallTalk was the first successful object oriented language and JAVA was built on its characteristics. Alan Kay (inventor of SmallTalk) put forth the following 5 guidelines for object-oriented programming: 1. Everything is an object. You can take any conceptual component in the problem you re trying to solve and represent it as an object in your program. 2. A program is a bunch of objects telling each other what to do by sending messages. Think of a message as a request to call a method that belongs to a particular object. 3. Each object has its own memory made up of other objects. Put another way, you create a new kind of object by making a package containing existing objects. Thus, you can build complexity into a program while hiding it behind the simplicity of objects. 20

Thinking in JAVA 4. Every object has a type. Each object is an instance of a class, in which class is synonymous with type. 5. All objects of a particular type can receive the same messages. This is actually a loaded statement, as you will see later. Because an object of type circle is also an object of type shape, a circle is guaranteed to accept shape messages. This means you can write code that talks to shapes and automatically handle anything that fits the description of a shape. This substitutability is one of the powerful concepts in OOP. 21

Program elements Some final notes before we start with a very simple JAVA program. The basic structure of a JAVA program is similar to a SmallTalk program Data or variables defined within a class are called instance variables. Code is contained within methods. Variables and methods constitute the class. Important Note: A JAVA application must have a main method. The main method is treated as the entry point for execution. 22

Kickoff: Your first program in JAVA /* HelloWorld.java Code for the HelloWorld application */ import java.lang.*; public class HelloWorld { //importing basic language //functions in the java package //class HelloWorld public static void main(string[ ] args) //main function { System.out.print("Hello world! This is my first JAVA program!"); //display the String } } //end class HelloWorld 23

Compiling & Execution ECE208, ECE226 Write your JAVA program using TextPad. Make sure to save the file with a.java extension To compile the program go to Tools -> Compile JAVA (or) press CTRL+1 To run the program after compilation go to Tools -> Run JAVA application (or) press CTRL+2 The output is visible in a terminal window which opens up on execution. From home Download TextPad: https://sitelicense.arizona.edu/ JAVA SDK: http://java.sun.com/j2se/1.4.2/download.html 24

Program Analysis - Comments in JAVA code /* text */ The compiler ignores everything from /* to */. /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */ (The Java Developers Kit s javadoc tool uses doc comments when preparing automatically generated documentation) // text The compiler ignores everything from // to the end of the line. 25

Program Analysis - Importing Packages A package is a collection of related classes and interfaces providing access protection and namespace management. In JAVA, packages are stored in a hierarchical manner (in the java package) and are explicitly imported into new class definitions. Syntax for importing packages: import pckg1[.pckg2].(classname/*); For example: import java.util.*; Example classes: Date, Arrays, Stack, LinkedList import java.lang.math; Example methods: abs( ), exp( ), floor( ), pow( ) Other packages: javax.swing.*; java.awt.* etc. Complete class reference: http://java.sun.com/j2se/1.4.2/docs/api/ 26

Importing Packages (Contd ) Basic class functions are stored in the package java.lang. This package is implicitly imported by the compiler for all programs. So the following line can be omitted from the HelloWorld.java program: import java.lang.*; Additional classes need to be imported at the beginning of the program. 27

Program Analysis Naming convention In JAVA, all the code resides inside a class. By convention the class s name should match the name of the file that holds the program Hence, for the HelloWorld class, the filename has to be HelloWorld.java Note: In JAVA, { } braces are used to define a block of code for classes, methods and local scopes 28

Program Analysis The main method Every Java application must contain a main method as this is the line at which the program will begin executing. public static void main(string[ ] args) public indicates that the main method can be accessed by code outside the class in which it id declared. static (discussed ahead) void indicates that the main method doesn't return any value. The main method accepts a single argument: an array of type String. This array is the mechanism through which the runtime system passes information to your application. (command-line arguments) 29

Program Analysis Static keyword A class normally doesn t have physical existence unless its object is initialized. The static keyword implies that data or method is not tied to any particular object instance of a class. So even if you ve never created an object of that class you can call a static method or access a piece of static data. With ordinary, non-static data and methods, you must create an object and use that object to access the data or method, since non-static data and methods must know the particular object they are working with 30

Program Analysis System class The following code prints the string Hello world! This is my first JAVA program! on the screen. System.out.print("Hello world! This is my first JAVA program!"); System is a predefined class that represents the system on which the program executes. out is an object reference to a PrintStream object that represents standard output. PrintStream is a class with a method called print( ) which prints a string to the standard output. In this case, standard output is the terminal screen. 31

Summing up. What we learnt so far: Key features of OOP Thinking in JAVA Basic program structure Looking Ahead:- A Little JAVA: A quick programming reference Inheritance and Polymorphism Program Development Case Study Java Database Connectivity 32