580 likes | 702 Views
Java Program = collection of Classes. Class::Object. instances of the class. abstract concept. BankAccount::BankAccountOfJohnSmith#127. Defining a class. class class-name [extends superclass name] [implements interface name] { [Declaration of variables]
E N D
Java Program = collection of Classes Class::Object instances of the class abstract concept BankAccount::BankAccountOfJohnSmith#127
Defining a class class class-name [extends superclass name] [implements interface name] { [Declaration of variables] [Declaration of methods] }
Instance variables (file Book.java) 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; ...
Instance variables (file ToyBankAccount.java) 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; ...
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 public boolean withdrawMoney(int pin,double amount) { if (pin==this.pin) { if (checkingBalance>amount) { checkingBalance-=amount; return true; } } return false; } formal parameters actual parameters withdrawalOK=johnsAccount.withdrawMoney(7534,500); object method
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 public void depositMoney(double amount) { checkingBalance+=amount; } johnsAccount.depositMoney(500);
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. default constructor is public ToyBankAccount() {}
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 pin) { savingsAcount=penalty=checkingInitialAmount=0; this.pin=pin; this.ownersName=new String(ownersName); } public ToyBankAccount(String ownersName, int checkingInitialAmount, int pin) { checkingAmount=checkingInitialAmount; savingsAcount=penalty=0; this.pin=pin; this.ownersName=new String(ownersName); }
Constructor - this() public ToyBankAccount(String ownersName, int pin) { this(ownersName,0,pin); } (must be first statement) public ToyBankAccount(String ownersName, int checkingInitialAmount, int pin) { checkingAmount=checkingInitialAmount; savingsAcount=penalty=0; this.pin=pin; this.ownersName=new String(ownersName); }
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; ... }
public/private for instance variables 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
Accessor/Mutator methods 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; } }
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
Variables int x; of primitive type of class type ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(“John Smith”,0,1234); ToyBankAccount marysAccount=johnsAccount; marysAccount.depositMoney(1000); System.out.println(“”+johnsAccount.balance())
Variables ToyBankAccount johnsAccount; johnsAccount=new ToyBankAccount(“John Smith”,0,1234); ToyBankAccount marysAccount=johnsAccount; marysAccount.depositMoney(1000); System.out.println(“”+johnsAccount.balance()) marysAccount johnsAccount 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 boolean equals(Book s) { return author.equals(s.author)&& title.equals(s.title)&& ... ; } You have to implement equals method if you want “deeper” equality testing for your class.
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 public void depositMoney(double amount) { checkingBalance+=amount; } johnsAccount.depositMoney(500); 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 initializer block 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; ... }
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); } (a.bigger(b)) public static boolean bigger(Account a,Account b) { return (a.balance>b.balance); } (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: 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(); } } 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); } } 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: What is the output? 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));
EXERCISE #5: What is the output? 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));