Introduction to Java Programming

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed.
UML Class Diagram: class Rectangle
Chapter 10: Inheritance and Polymorphism
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Netprog 2002 Java Intro1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network.
Lecture 5 Java Introduction CPE 401 / 601 Computer Network Systems slides are modified from Ricky Sethi.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
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.
Introduction to java Prepared By:-Pragnesh Patel Lect. In Computer Dept. NSIT,Jetalpur 1.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
1 Introduction to Java. 2 What is Java? A programming language. A platform –A virtual machine (JVM) definition. –Runtime environments in diverse hardware.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Structured Programming Good for programming in the small Often doesn't scale up Limitations –Changes at top may affect lower-level algorithms –Code reuse.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Object Oriented Programming Lecture 2: BallWorld.
Spring 2006 Special Topics in Computer Engineering: Java Intro 1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Information and Computer Sciences University of Hawaii, Manoa
Modern Programming Tools And Techniques-I
Concurrent Object-Oriented Programming Java (VRH 7.7,8.6)
JAVA MULTIPLE CHOICE QUESTION.
Chapter 4 Assignment Statement
Inheritance and Polymorphism
Chapter 11: Inheritance and Polymorphism
Lecture 2: Data Types, Variables, Operators, and Expressions
University of Central Florida COP 3330 Object Oriented Programming
Chapter 3 Assignment Statement
Programming Language Concepts (CIS 635)
UML Class Diagram: class Rectangle
Modern Programming Tools And Techniques-I Inheritance
Computer Science II Exam 1 Review.
Starting JavaProgramming
null, true, and false are also reserved.
Java Programming Language
Introduction to Java Programming
Polymorphism CT1513.
Week 6 Object-Oriented Programming (2): Polymorphism
The Building Blocks Classes: Java class library, over 1,800 classes:
CS201: Data Structures and Discrete Mathematics I
Java – Inheritance.
Inheritance CT1513.
CIS 199 Final Review.
Chapter 8 Class Inheritance and Interfaces
Chap 2. Identifiers, Keywords, and Types
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Introduction to Java Programming

First Program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); }

Compiling and Running HelloWorld.java HelloWorld.class javac HelloWorld.java HelloWorld.java compile source code run HelloWorld.class java HelloWorld bytecode

Java Data Types Primitive Data Types: Reference types boolean true or false char unicode! (16 bits) byte signed 8 bit integer short signed 16 bit integer int signed 32 bit integer long signed 64 bit integer float,double IEEE 754 floating point Reference types Arrays Strings Objects

Operators & Control Structures Assignment: =, +=, -=, *= Numeric: +, -, *, /, %, ++, -- Relational: ==,!=, <, >, <=, >= Boolean: &&, ||, ! Bitwise: &, |, ^, ~, <<, >> class Sample { public static void main(String[] args) { int number = 0; if (number > 0) { System.out.println("Number is positive."); } else { System.out.println("Number is negative."); for(number=0;number<10;number++) System.out.println(number); while(number>0) conditional: if if else switch loop: while for do break and continue

Exceptions Terminology: throw an exception: signal that some condition (possibly an error) has occurred. catch an exception: deal with the error (or whatever). try { // code that can throw an exception } catch (Exception e) { // code to handle other exceptions } finally { // code to run after try or any catch }

Classes and Objects All Java statements appear within methods, and all methods are defined within classes. One top level public class per .java file. typically end up with many .java files for a single program. One (at least) has a static public main() method. Class name must match the file name! compiler/interpreter use class names to figure out what file name is.

Classes and Objects User-defined data types Defined using the “class” keyword Each class has associated Data members (any object type) Methods that operate on the data New instances of the class are declared using the “new” keyword “Static” members/methods have only one copy, regardless of how many instances are created

Sample Class & Constructor public class Point { private double x,y; public Point() { x=y=0; } public Point(double x, double y) { this.x = x; this.y=y; public double distanceFromOrigin(){ return Math.sqrt(x*x+y*y);

Objects and new You can declare a variable that can hold an object: Point p; but this doesn’t create the object! You have to use new: Point p = new Point(3.1,2.4); Strings are special. You can initialize Strings like this: String blah = "I am a literal "; Using objects object.method() object.field

Arrays Arrays are supported as a second kind of reference type (objects are the other reference type). creating an array requires new int x[] = new int[1000]; byte[] buff = new byte[256]; float[][] mvals = new float[10][10]; int[] foo = {1,2,3,4,5}; String[] names = {“Joe”, “Sam”}; Point [] p=new Point[3]; p[0]=new Point(5,2); p[1]=new Point(1,1);

Notes on Arrays index starts at 0. arrays can’t shrink or grow. e.g., use Vector instead. Arrays have a .length int[] values; int total=0; for (int i=0;i<value.length;i++) { total += values[i]; }

Reference Types Objects and Arrays are reference types Primitive types are stored as values. Reference type variables are stored as references (pointers that we can’t mess with). There are significant differences! int x=3; int y=x; Point p = new Point(2.3,4.2); Point t = p;

Passing arguments to methods Primitive types: the method gets a copy of the value. Changes won’t show up in the caller. Reference types: the method gets a copy of the reference, the method accesses the same object! int sum(int x, int y) { x=x+y; return x; } void increment(int[] a) { for (int i=0;i<a.length;i++) a[i]++;

Comparing Reference Types Comparison using == means: “are the references the same?” (do they refer to the same object?) Sometimes you just want to know if two objects/arrays are identical copies. use the .equals() method you need to write this for your own classes!

Packages You can organize a bunch of classes and interfaces into a package. defines a namespace that contains all the classes. You need to use some java packages in your programs java.lang java.io java.util import java.io.File

Inheritance and Polymorphism “is-a” relationship Subclass is derived from one existing class (superclass) public class Student { String name; char gender; Date birthday; Vector<Grade> grades; double getGPA() { … } int getAge(Date today) { public class Professor { String name; char gender; Date birthday; Vector<Paper> papers; int getCiteCount() { … } int getAge(Date today) {

Inheritance and Polymorphism public class Person { String name; char gender; Date birthday; int getAge(Date today) { … } public class Student { String name; char gender; Date birthday; Vector<Grade> grades; double getGPA() { … } int getAge(Date today) { public class Professor { String name; char gender; Date birthday; Vector<Paper> papers; int getCiteCount() { … } int getAge(Date today) {

Inheritance modifier(s) class ClassName extends ExistingClassName { memberList } public class Circle extends Shape { . }

Inheritance public class Rectangle { public int Height,Width; . . . } public class Box extends Rectangle { public int Length; . . . }

Inheritance Subclasses have all of the data members and methods of the superclass Subclasses can add to the superclass Additional data members Additional methods Subclasses are more specific and have more functionality Superclasses capture generic functionality common across many types of objects

Overriding Methods A subclass can override (redefine) the methods of the superclass Objects of the subclass type will use the new method Objects of the superclass type will use the original

Overriding Methods public class Rectangle { public int Length,Width; public double area() return Length * Width; } public class Box extends Rectangle { public int Height; public double area() return 2*(Length*Width+ Length*height +Width*Height); }

Final Methods Can declare a method of a class final using the keyword final public final void doSomeThing() { //... } If a method of a class is declared final, it cannot be overridden with a new definition in a derived class Can also declare a class final using the keyword final

Calling methods of the superclass To write a method’s definition of a subclass, specify a call to the public method of the superclass If subclass overrides public method of superclass, specify call to public method of superclass: super.MethodName(parameter list) If subclass does not override public method of superclass, specify call to public method of superclass: MethodName(parameter list)

Calling methods of the superclass class Box public void setDimension(double l, double w, double h) { super.setDimension(l, w); if (h >= 0) height = h; else height = 0; }

Defining Constructors of the Subclass Call to constructor of superclass: Must be first statement Specified by super parameter list public Rectangle() { width=length = 0; } public Rectangle(double l, double w) { width=w; length = l; } public Box() { super(); height = 0; } public Box(double l, double w, double h) super(l, w); height = h;

Access Control Access control keywords define which classes can access classes, methods, and members Modifier Class Package Subclass World public Y protected N private

Polymorphism Late binding or dynamic binding (run-time binding): Method to be executed is determined at execution time, not compile time Polymorphism: to assign multiple meanings to the same method name Implemented using late binding

Polymorphism Can treat an object of a subclass as an object of its superclass A reference variable of a superclass type can point to an object of its subclass Person p1; PartTimeEmployee p2; p1 = new Person("John", "Blair"); p2 = new PartTimeEmployee("Susan","Johnson",12.50,45); p1 = p2; System.out.println(p1.toString()); Susan Johnson wages are: $562.5

Polymorphism and References Shape myShape = new Circle(); // allowed Shape myShape2 = new Rectangle(); // allowed Rectangle myRectangle = new Shame(); // NOT allowed

Polymorphism Operator instanceof: determines whether a reference variable that points to an object is of a particular class type This expression evaluates to true if p points to an object of the class BoxShape; otherwise it evaluates to false: p instanceof BoxShape

Abstract Methods A method that has only the heading with no body Must be implemented in a subclass Must be declared abstract public double abstract area(); public void abstract print(); public abstract object larger(object); void abstract insert(int insertItem);

Abstract Classes A class that is declared with the reserved word abstract in its heading An abstract class can contain instance variables, constructors, finalizers, and non-abstract methods An abstract class can contain abstract methods If a class contains an abstract method, the class must be declared abstract You cannot instantiate an object of an abstract class type; can only declare a reference variable of an abstract class type You can instantiate an object of a subclass of an abstract class, but only if the subclass gives the definitions of all the abstract methods of the superclass

Abstract Class Example public abstract class AbstractClassExample { protected int x; public void abstract print(); public void setX(int a) x = a; } public AbstractClassExample() x = 0;

Interfaces A class that contains only abstract methods and/or named constants To be able to handle a variety of events, Java allows a class to implement more than one interface

Composition One or more members of a class are objects of another class type “has-a” relation between classes For example, “every person has a date of birth”

Concurrent Programming Java is multithreaded! threads are easy to use. Two ways to create new threads: Extend java.lang.Thread Overwrite “run()” method. Implement Runnable interface Include a “run()” method in your class. Starting a thread new MyThread().start(); new Thread(runnable).start();

The synchronized Statement Java is multithreaded! threads are easy to use. Instead of mutex, use synchronized: synchronized ( object ) { // critical code here } You can also declare a method as synchronized: synchronized int blah(String x) { // blah blah blah }