Java Program = collection of Classes Class::Object abstract concept instances of the class BankAccount::BankAccountOfJohnSmith#127.

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

Written by: Dr. JJ Shepherd
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.
Last lecture classes and objects instance variables (fields) instance methods parameters – formal parameter, actual parameters return type, void class.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Access to Names Namespaces, Scopes, Access privileges.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Enhancing classes Visibility modifiers and encapsulation revisited
Terms and Rules Professor Evan Korth New York University (All rights reserved)
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Java Methods. Topics  Declaring fields vs. local variables  Primitive data types  Strings  Compound Assignment  Conversions from one value to another.
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.
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.
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.
Introduction to Java Java Translation Program Structure
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Programming Languages and Paradigms Activation Records in Java.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
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 & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Topics Instance variables, set and get methods Encapsulation
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Chapter 9 A Second Look at Classes and Objects - 4.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Topic: Classes and Objects
Object-Oriented Concepts
JAVA MULTIPLE CHOICE QUESTION.
Data Structures and Algorithms revision
Chapter 7 User-Defined Methods.
Lecture 17: Polymorphism (Part II)
The Building Blocks Classes: Java class library, over 1,800 classes:
Introduction to Objects
CS2011 Introduction to Programming I Objects and Classes
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
Namespaces, Scopes, Access privileges
Programs and Classes A program is made up from classes
Lecture 18: Polymorphism (Part II)
JAVA CLASSES.
Classes, Objects and Methods
OO Programming Concepts
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
First Semester Review.
Chapter 7 Objects and Classes
Presentation transcript:

Java Program = collection of Classes Class::Object abstract concept instances of the class BankAccount::BankAccountOfJohnSmith#127

class class-name [extends superclass name] [implements interface name] { [Declaration of variables] [Declaration of methods] } Defining a class

Instance variables public class Book { public String title,author,publisher; public int pages; public double price;... } Book textbook=new Book(); textbook.title=“JAVA – Introduction to CS and programming”; textbook.author=“W. Savitch”; textbook.publisher=“Prentice Hall”; textbook.pages=1052;... (file Book.java)

Instance variables public class ToyBankAccount { public String ownersName; public double savingsBalance,checkingBalance; public double penalty; public int pin;... } ToyBankAccount johnsAccount; johnsAccount=new BankAccount(); johnsAccount.ownersName=“John Smith”; johnsAccount.savingsBalance=1000.0; johnsAccount.checkingBalance=500; johnsAccount.pin=7534;... (file ToyBankAccount.java)

Instance methods public class ToyBankAccount { /* * returns true if the withdrawal from checking is succesful */ public boolean withdrawMoney(int pin,double amount) { if (pin==this.pin) { if (checkingBalance>amount) { checkingBalance-=amount; return true; } return false; }

Instance methods public class ToyBankAccount { /* * returns true if the check clears. */ public boolean payCheck(double amount) { if (checkingBalance>amount) { checkingBalance-=amount; return true; } else { penalty+=25.0; return false; }

Instance methods public class ToyBankAccount { /* * returns true if the check clears. */ public boolean payCheck(double amount) { if (checkingBalance>amount) { checkingBalance-=amount; return true; } else { penalty+=25.0; return false; } Not a good programming practice!

Constants public class ToyBankAccount { public static final int PENALTY_FOR_CHECK_OVER_LIMIT=25; /* * returns true if the check clears. */ public boolean payCheck(double amount) { if (checkingBalance>amount) { checkingBalance-=amount; return true; } else { penalty+= PENALTY_FOR_CHECK_OVER_LIMIT; return false; }

Parameters withdrawalOK=johnsAccount.withdrawMoney(7534,500); formal parameters actual parameters objectmethod public boolean withdrawMoney(int pin,double amount) { if (pin==this.pin) { if (checkingBalance>amount) { checkingBalance-=amount; return true; } return false; }

Return type public boolean withdrawMoney(int pin,double amount) { if (pin==this.pin) { if (checkingBalance>amount) { checkingBalance-=amount; return true; } return false; } withdrawalOK=johnsAccount.withdrawMoney(7534,500);

Return type - void johnsAccount.depositMoney(500); public void depositMoney(double amount) { checkingBalance+=amount; }

Creating objects - new ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(); johnsAccount is a variable which can point to an object of type ToyBankAccount create a new object of type ToyBankAccount and let johnsAccount point to it

Constructor ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(); Call to a special method of the class – constructor. public ToyBankAccount() {} default constructor is

Constructor public ToyBankAccount(String ownersName, double checkingInitialAmount, int pin) { checkingAmount=checkingInitialAmount; savingsAcount=penalty=0; this.pin=pin; this.ownersName=new String(ownersName); } ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(“John Smith”,0,1234);

Constructor - overloading public ToyBankAccount(String ownersName, int checkingInitialAmount, int pin) { checkingAmount=checkingInitialAmount; savingsAcount=penalty=0; this.pin=pin; this.ownersName=new String(ownersName); } public ToyBankAccount(String ownersName, int pin) { savingsAcount=penalty=checkingInitialAmount=0; this.pin=pin; this.ownersName=new String(ownersName); }

Constructor - this() public ToyBankAccount(String ownersName, int checkingInitialAmount, int pin) { checkingAmount=checkingInitialAmount; savingsAcount=penalty=0; this.pin=pin; this.ownersName=new String(ownersName); } public ToyBankAccount(String ownersName, int pin) { this(ownersName,0,pin); } (must be first statement)

public/private for instance variables public – anybody can access private – only methods of the class can access public class ToyBankAccount { public String ownersName; public double savingsBalance,checkingBalance; public double penalty; public int pin;... }

ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(“John Smith”,100,1234); johnsAccount.savingsAccount+=50; Not good. Suppose that we want to modify the code to store all transactions. Have to find all occurences of public/private for instance variables

public – anybody can access private – only methods of the object can access public class ToyBankAccount { private String ownersName; private double savingsBalance,checkingBalance; private double penalty; private int pin;... } Instance variables should be private

public class Book { private String title,author,publisher; private int pages; private double price; public String getTitle() { return title; } public void setTitle(String title) { this.title=title; } Accessor/Mutator methods

public for classes in each file: one public class with the same name as the filename any number of classes which are visible only to classes in the file

ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(“John Smith”,0,1234); Variables of primitive type of class type int x; ToyBankAccount marysAccount=johnsAccount; marysAccount.depositMoney(1000); System.out.println(“”+johnsAccount.balance())

ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(“John Smith”,0,1234); ToyBankAccount marysAccount=johnsAccount; marysAccount.depositMoney(1000); System.out.println(“”+johnsAccount.balance()) Variables marysAccountjohnsAccount int x; x=10; int y=x; y+=10

Privacy leaks private Address ownersAddress ; public Address getOwnersAddress() { return ownersAddress; } address=johnsAccount.getOwnersAddress(); address.set(“John Evil,....”);

Privacy leaks private Address ownersAddress ; public Address getOwnersAddress() { return new Address(ownersAddress); } address=johnsAccount.getOwnersAddress(); address.set(“John Evil,....”);

null ToyBankAccount johnsAccount=null; does not point to any object...

“null Pointer Exception” error johnsAccount.depositMoney(100);

==, = and equals for variables of class type == tests whether they point to the same object. String s=“abc”, t=“abc”; if (s==t) system.out.println(“You win $1,000,000”);

==, = and equals for variables of class type == tests whether they point to the same object. String s=“abc”, t=“abc”; if (s.equals(t)) system.out.println( “You were chosen for the next round!”); You have to implement equals method if you want “deeper” equality testing for your class.

==, = and equals You have to implement equals method if you want “deeper” equality testing for your class. boolean equals(Book s) { return author.equals(s.author)&& title.equals(s.title)&&... ; }

Method overloading public void depositMoney(double amount,Currency currency) { checkingBalance+=Currency.Convert(amount,currency,Currency.USD); } public void depositMoney(double amount) { checkingBalance+=amount; } JohnsAccount.depositMoney(100,Currency.SKK); JohnsAccount.depositMoney(100);

Method overloading public void depositMoney(double amount,Currency currency) { checkingBalance+=Currency.Convert(amount,currency,Currency.USD); } public void depositMoney(double amount) { checkingBalance+=amount; } public void depositMoney(double amountInSkk) { checkingBalance+=amount*50; }

Method overloading public void depositMoney(double amount,Currency currency) { checkingBalance+=Currency.Convert(amount,currency,Currency.USD); } public void depositMoney(double amount) { checkingBalance+=amount; } public char depositMoney(double amountInSkk) { checkingBalance+=amount*50; } cannot overload based on the returned type

Automatic conversion johnsAccount.depositMoney(500); public void depositMoney(double amount) { checkingBalance+=amount; } int

Class variables public class ToyBankAccount { private static int totalAccounts=0; private static totalAccountBalance; private String ownersName; private double savingsBalance,checkingBalance; private double penalty; private int pin;... }

Class variables public class ToyBankAccount { private static int totalAccounts=0;{totalAccounts++;} private static totalAccountBalance; private String ownersName; private double savingsBalance,checkingBalance; private double penalty; private int pin;... } initializer block

Class variables public class ToyBankAccount { private static final int PENALTY_FOR_CHECK_OVER_LIMIT=25; private static int totalAccounts=0; private static totalAccountBalance; private String ownersName; private double savingsBalance,checkingBalance; private double penalty; private int pin;... }

Class methods public class ToyBankAccount { private static final int PENALTY_FOR_CHECK_OVER_LIMIT=25; private static int totalAccounts=0; private static double totalAccountBalance;..... public static AverageBalance() { return totalAccountBalance/totalAccounts; }

Class methods public static AverageBalance() public endOfMonthUpdate() { if (balance>AverageBalance()) balance+=BONUS; } class methods cannot use instance fields or methods

Class methods public static AverageBalance() class Bank { public monthlyReport() { system.out.print(Account.AverageBalance()); }

Class methods example - Math Math.sqrt() can use to group methods which have something in common

Instance vs Class methods public boolean bigger(Account a) { return (balance>a.balance); } public static boolean bigger(Account a,Account b) { return (a.balance>b.balance); } (a.bigger(b)) (Account.bigger(a,b))

main public static void main(String[] args) { } can be defined for any class, not just for the one that is running (good for debugging)

Garbage collection ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(“John Smith”,0,1234); johnsAccount=null;

EXERCISE #1: public class ToyBankAccount { private String ownersName; private double savingsBalance,checkingBalance; private double penalty; private int pin;... } 1a) implement method transferSavingToChecking 1b) implement method transferToAccount 1c) implement method transferBetweenAccounts (takes two accounts and amount)

Default initialization instance variables are initialized to the default value (zero for numerical classes, false for boolean) (this is not true for local variables (i.e. variables declared in methods))

EXERCISE #2: Class Test { private int x,y; public Test(int x,int y) { x=x; this.y=y; System.out. println(“”+x+”,”,y); } public Values() { System.out. println(“”+x+”,”+y); } public class Runs { public main(String[] args) { Test r,p; r=new Test(2,3); r.Values(); p=r; p=new Test(3,4); r.Values(); } What is the output?

EXERCISE #3: public class Runs { public main(String) { int x=14,y=7,z=5,i; for (i=0;i<300;i++) { x = x+y+z; y = x-y-z; z = x-y-z; x = x-y-z; } System.out(“”+x+”,”+y+”,”+z); } What is the output?

EXERCISE #4: public class MyClass { private int data; public boolean equals(MyClass a) { return (this==a) } public MyClass(int x) { data=x; } } MyClass a,b; a=new MyClass(3); b=a; System.out.println(a.equals(b)); b=new MyClass(3); System.out.println(a.equals(b)); What is the output?

EXERCISE #5: public class MyClass { private int data; public boolean equals(MyClass a) { return (this.data==a.data) } public MyClass(int data) { data=data; } } MyClass a,b; a=new MyClass(3); b=a; System.out.println(a.equals(b)); b=new MyClass(4); System.out.println(a.equals(b)); What is the output?

EXERCISE #6: public class MyClass { private String name; public boolean equals(MyClass a) { return (this.name==a.name) } public MyClass(String name) { this.name=name; } } MyClass a,b; a=new MyClass(“John”); b=a; System.out.println(a.equals(b)); b=new MyClass(“John”); System.out.println(a.equals(b)); What is the output?

public class myInt { public int x; } myInt a = new myInt(); a.x = 10; myInt b = a; System.out.println("a = "+a.x+"; b = "+b.x); b.x = 20; System.out.println("a = "+a.x+"; b = "+b.x); EXERCISE #7: What is the output?

public class myInt { public int x; public static void switch(myInt a,myInt b) { int c; c=a.x; a.x=b.x; b.x=c; } public static void switch(int a,int b) { int c; c=a; a=b; b=c; } myInt a = new myInt(); a.x = 10; myInt b = new myInt(); b.x = 20; myInt.switch(a.x,b.x); System.out.println("a = "+a.x+"; b = "+b.x); myInt.switch(a.b); System.out.println("a = "+a.x+"; b = "+b.x); EXERCISE #8: What is the output?

public class myString{ public String x; public static void switch(myInt a,myInt b) { String c; c=a.x; a.x=b.x; b.x=c; } public static void switch(String a,String b) { String c; c=a; a=b; b=c; } myString a = new myString(); a.x = “10”; myString b = new myString(); b.x = “20”; myString.switch(a.x,b.x); System.out.println("a = "+a.x+"; b = "+b.x); myString.switch(a.b); System.out.println("a = "+a.x+"; b = "+b.x); EXERCISE #9: What is the output?

EXERCISE #10: What is the output? class Test { public int x; public static int y; public Test(int x,int y) { this.x=x; this.y=y; } } Test a,b; a=new Test(3,4); System.out.println(""+a.x+","+a.y); b=new Test(5,6); System.out.println(""+b.x+","+b.y); System.out.println(""+a.x+","+a.y);

EXERCISE #11: What is the output? public class Test { static Test first=null; Test next; public int x; public Test(int x) { this.x=x; next=first; first=this; } public static void list() { for (Test p=first;p!=null;p=p.next) System.out.println(" "+p.x); } public static void main(String[] args) { Test a=new Test(2),b=new Test(3),c=new Test(4); Test.list(); }

EXERCISE #12: Where is the error? public class Test { Test next; public int x; public void print() { int y; while (y<10) { System.out.println(x+y); y++; } public static void main(String[] args) { Test a=new Test(); a.print(); }

EXERCISE #13: Where are the errors public class Test { Test next; public int x; public Test(int x) { Test.x=x; } public static void main(String[] args) { double y=1; Test a=new Test(y); }