CS260 Intro to Java & Android 03.Java Language Basics

Similar documents
Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

1 Shyam sir JAVA Notes

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Introduction to Programming Using Java (98-388)

Java Programming Tutorial 1

Java Primer 1: Types, Classes and Operators

Lesson: Classes and Objects

Programming overview

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Inheritance. The Java Platform Class Hierarchy

Index COPYRIGHTED MATERIAL

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

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Java Notes. 10th ICSE. Saravanan Ganesh

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java: introduction to object-oriented features

Computer Science II (20073) Week 1: Review and Inheritance

Operators and Expressions

Java Object Oriented Design. CSC207 Fall 2014

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

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

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 Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Brief Summary of Java

Java Bytecode (binary file)

CMSC 132: Object-Oriented Programming II

Java Fundamentals (II)

Class, Variable, Constructor, Object, Method Questions

CLASS DESIGN. Objectives MODULE 4

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

15CS45 : OBJECT ORIENTED CONCEPTS

Chapter 6 Introduction to Defining Classes

Computer Science 210: Data Structures

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Operators. Java operators are classified into three categories:

Lexical Considerations

Java enum, casts, and others (Select portions of Chapters 4 & 5)

COP 3330 Final Exam Review

3. Java - Language Constructs I

4 Programming Fundamentals. Introduction to Programming 1 1

What is Inheritance?

Lecture 2: Java & Javadoc

Program Fundamentals

OVERRIDING. 7/11/2015 Budditha Hettige 82

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Chapter 3: Operators, Expressions and Type Conversion

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

c) And last but not least, there are javadoc comments. See Weiss.

Programming with Java

More On inheritance. What you can do in subclass regarding methods:

Operators in java Operator operands.

Super-Classes and sub-classes

Getting started with Java

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

STRUCTURING OF PROGRAM

CS-202 Introduction to Object Oriented Programming

The Java language has a wide variety of modifiers, including the following:

Chapter 5 Object-Oriented Programming

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

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

C++ Important Questions with Answers

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

WA1278 Introduction to Java Using Eclipse

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

9 Working with the Java Class Library

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

CHAPTER 7 OBJECTS AND CLASSES

Full file at

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lexical Structure (Chapter 3, JLS)

Full file at

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

INHERITANCE. Spring 2019

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Preview from Notesale.co.uk Page 9 of 108

Points To Remember for SCJP

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Computer Science II (20082) Week 1: Review and Inheritance

Objects and Iterators

Java Programming Training for Experienced Programmers (5 Days)

Fall 2017 CISC124 9/16/2017

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

A Short Summary of Javali

UNIT- 3 Introduction to C++

Inheritance (Outsource: )

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

13 th Windsor Regional Secondary School Computer Programming Competition

OBJECT ORİENTATİON ENCAPSULATİON

Transcription:

03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1

What is the distinction between fields and variables? Java has the following kinds of variables: Instance Variables (Non-Static Fields) variables whose values are unique to each instance of a class Class Variables (Static Fields) variables declared with the static modifier which tells the compiler exactly one copy of this variable exists Local Variables a variable declared between the opening and closing brace of a method Parameters variables that are arguments to a method fields fields in general exclude local variables and parameters variables are all of the above 2

P1: List the instance variables, class variables, local variables, and parameters for the class Rational. 3

Primitive Data Types byte short int long float double boolean char 8-bit signed number 16-bit signed number 32-bit signed number 64-bit signed number 32-bit IEEE 754 floating-point number 64-bit IEEE 754 floating-point number either true or false 16-bit Unicode character String String is an object and NOT a primitive data type 4

Primitive Datatypes versus Objects Explain the specifics of what is going on in the following Java code: 5

What is the output? Draw the activation record (AR). 6

What must be happening? 7

Default Values Fields that are declared but not initialized are set to a reasonable default value by the compiler. Data Type byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' String (or any null object) boolean FALSE Default Value (for fields) Note: The compiler never assigns a default value to an uninitialized local variable. Accessing an uninitialized local variable is a compiler error. 8

Literals boolean bisfound = false; char ch = 'C'; byte b = 100; short s = 10000; int i = 100000; long l = 100L; int decval = 26; // The number 26, in decimal int octval = 032; // The number 26, in octal int hexval = 0x1a; // The number 26, in hexadecimal double d1 = 123.4; double d2 = 1.234e2; float f1 = 123.4f; // the default value 123.4 is a double You should be noticing many similarities to C++ yet enough subtle differences that will make coding somewhat frustrating at first. 9

array is a container object that holds a fixed number of values of a single type container a class used to contain other Java objects. A container class has methods for adding and deleting objects as well as aiding in iteration. class Foo { public static void main (String[] args) { int[] intarray; // int intarray[]; OK, don t use intarray = new int[10]; intarray[5] = 99; System.out.println ("Value = " + intarray[5]); 10

Arrays are objects are dynamically created can be assigned to variables of type Object can use all methods of Object int[] intarray; // int intarray[]; OK, don t use intarray = new int[10]; for (int i = 0; i < intarray.length; ++i) { intarray[i] = 0; } 11

Problem: Create a class RationalSet in the package edu.pacificu.cs.rational that is able to store Rational objects in an array. Create the following methods: 1) default constructor that creates space for an array of 100 Rational objects 2) a constructor that accepts an integer numrationals and creates space for that many Rational objects 3) size returns the number of elements in the set 12

Operator Precedence Operators Precedence postfix expr++ expr-- unary ++expr --expr +expr -expr ~! multiplicative * / % additive + - shift << >> >>> relational < > <= >= instanceof equality ==!= bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR logical AND && logical OR ternary? : assignment = += -= *= /= %= &= ^= = <<= >>= >>>= 13

Note1: All binary operators are left associative except the assignment operator is right associative Note2: Watch out for things like: byte b1 = 0, b2 = 1, b3; b3 = b1 + b2; // not allowed // must type cast b3 = (byte) (b1 + b2); There are too many of these to mention so read the tutorials closely!!!! I would suggest that we use int and double for most of our code to avoid mixed mode arithmetic. 14

Declaring Classes // simple class declaration class MyClass1 { // class body begins // field(s) // constructor(s) // method(s) } // class body ends // more complicated class declaration class MyClass2 extends MySuperClass implements MyInterface { // class body begins // field(s) // constructor(s) // method(s) } // class body ends 15

class declaration In general, class declarations can include the following components in order: 1. Modifiers such as public, private, and a number of others that you will encounter later. 2. The class name, with the initial letter capitalized by convention. 3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 5. The class body, surrounded by braces, {}. 16

Access Modifiers public modifier the field is accessible from all classes. private modifier the field is accessible only within its own class. public class Bicycle { private int mcadence; private int mgear; private int mspeed; public Bicycle(int startcadence, int startspeed, int startgear) { mgear = startgear; mcadence = startcadence; mspeed = startspeed; } 17

Defining Methods The only required elements of a method declaration are: the method's return type the method s name a pair of parentheses, () a body between braces, {} 18

Defining Methods Method declarations have six components, in order: 1. Modifiers such as public, private, and others you will learn about later. 2. The return type the data type of the value returned by the method, or void if the method does not return a value. 3. The method name the rules for field names apply to method names as well, but the convention is a little different. 4. The parameter list in parenthesis a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. 5. An exception list to be discussed later. 6. The method body, enclosed between braces the method's code, Winter including 2018 the declaration CS260 of local Intro to Java variables, & Android goes here. 19

Overloading Methods public class DataArtist {... public void draw(string s) {... } public void draw(int i) {... } public void draw(double f) {... } public void draw(int i, double f) {... } } 1. Overloaded methods are differentiated by the number and the type of the arguments passed into the method 2. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. 20

Garbage Collecting Java platform allows you to create as many objects as you want and you don't have to worry about destroying them The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection An object is eligible for garbage collection when there are no more references to that object. 21

Controlling Access class - if declared public, the class is visible to all classes. If no modifier exists, the class is visible to all classes within the same package class member access by other classes. A class member can have a modifier of: public, protected, no modifier, or private 22

Consider the following figure: The table below shows where the members of the class Alpha are visible for each of the access modifiers that can be applied Visibility Modifier Alpha Beta AlphaSub Gamma public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N 23

Inheritance 1. A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). 2. The class from which the subclass is derived is called a superclass (also a base class or a parent class). 3. Excepting class Object, which has no superclass, every class has one and only one direct superclass (single inheritance). 4. In the absence of any other explicit superclass, every class is implicitly a subclass of Object. 24

The Object class, defined in the java.lang package, defines and implements behavior common to all classes including the ones that you write. 25

Subclass Facts 1. The inherited fields can be used directly (depending on the controlling access), just like any other fields. 2. You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). 3. You can declare new fields in the subclass that are not in the superclass. 4. The inherited methods can be used directly as they are. 26

Subclass Facts 5. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. 6. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. 7. You can declare new methods in the subclass that are not in the superclass. 8. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. 27

Polymorphism is the capability of a method to perform different actions based on the object being acted upon Q1: Overloading and overriding are two different types of polymorphism. What is the difference between overloading and overriding? With polymorphism, the programmer can deal in generalities while the execution environment handles the specifics. Note: If a superclass reference is aimed at a subclass object, it is a compiler error attempting to reference a subclass-only member. Java Project: Polymorphism 28

Abstract Class declares the common functionality (state and behavior)of all classes in a class hierarchy An abstract class usually contains one or more abstract methods that must be overridden by a subclass One cannot instantiate an object of an abstract class public abstract class Employee public abstract double computepay (); Note1: If a class contains an abstract method, the class must be declared abstract Note2: Any child class must either override the abstract method or declare itself abstract 29

More important tidbits: Important packages include: java.util java.math java.io java.lang If you actually want to check if one object is equal to another object, visit these sites: http://www.ensta.fr/~diam/java/online/notesjava/data/expressions/22compareobjects.html http://www.javaworld.com/community/node/1006 http://www.technofundo.com/tech/java/equalhash.html http://technologiquepanorama.wordpress.com/2009/02/12/use-of-hashcode-andequals/ 30