Presentation is loading. Please wait.

Presentation is loading. Please wait.

GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.

Similar presentations


Presentation on theme: "GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter."— Presentation transcript:

1 GETTING INPUT Simple I/O

2 Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter your age"); int age = scan.nextInt(); // Better to be safe System.out.println("Enter your school grade"); String gradeStr = scan.next(); // Exceptions covered in more detail later try { int grade = Integer.parseInt(gradeStr); } catch (NumberFormatException e) { System.out.println("That's not a number!"); }

3 INHERITANCE More OO Concepts

4 Inheritance Topics Basic Inheritance –BankAccount & SavingsAccount –extends, super, equals –access control Typecast, instanceof Polymorphism Abstract Classes

5 Inheritance Basics Models “is-a” relationship, same as C++ requires extends keyword All classes are children of class Object Object has several methods that are frequently overridden: –toString: returns a string that describes the state of the object, automatically called by System.out.println(objectRef); –clone: creates a deep copy of an object –equals: does a field-by-field comparison, returns boolean result –hashcode: if object will be used as a hash key QUICK EXERCISE: draw deep vs shallow copy

6 Simple Inheritance Example public class BankAccount { public BankAccount() { super(); // call superclass constructor - Object balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { double newBalance = balance + amount; if (newBalance >= 0) // we’ll cover error handling later balance = newBalance; } public void withdraw(double amount) { double newBalance = balance - amount; if (newBalance >= 0) balance = newBalance; } public double getBalance() { return balance; } private double balance; } could be protected, but easier maintenance if private

7 Simple Inheritance Example class SavingsAccount extends BankAccount { public SavingsAccount(double balance, double rate) { super(balance); // calls parent constructor interestRate = rate; } void addInterest() { // use getters/setters unless protected double interest = getBalance()* interestRate / 100; deposit(interest); } private double interestRate; } can’t directly update balance if private

8 Another use of super In BankAccount public String toString() { // note use of Double wrapper class method return Double.toString(balance); // could do return "Balance: " + balance; // another option is: // return getClass().getName() + balance; } In SavingsAccount public String toString() { return super.toString() + "Interest rate " + interestRate; } calls parent class method class object describes class & properties

9 More on Inheritance SavingsAccount collegeFund = new SavingsAccount(1000, 0.1); // parent variable can “point” to child object BankAccount anAccount = collegeFund; // all objects are children of Object Object anObject = collegeFund; collegeFund.addInterest(); // OK anAccount.addInterest(); //not OK

10 Typecasts If you know that a reference contains a specific type of object, you can perform a cast (will be an exception if you’re wrong) BankAccount myAccount = (BankAccount) anObject; Can use instanceof to test class type* if (anObject instanceof BankAccount) { BankAccount myAccount = (BankAccount) anObject; … } *will be used very sparingly with good object-oriented design – rely on polymorphism instead. instanceof includes subclass, getClass does not.

11 Object Method Examples – equals public boolean equals(Object otherObject) { if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; BankAccount account = (BankAccount) otherObject; return balance == account.balance; // should call super.equals first if you write an // equals for a subclass // instanceof sometimes used instead of // getClass(), but it would return true for a // subclass } What happens if you don’t override equals? You should override hashCode too… use Eclipse for this.

12 Polymorphism In Java, method calls are always determined by the type of the actual object, not the type of the object reference (unlike C++, where virtual keyword is needed)

13 Access control public – like C++, good for constants private – like C++, good for instance fields protected – like C++ but extends to package, convenient for inheritance package –all methods of classes in the same package have access –this is the default! (easy to forget) –OK if several classes in package collaborate, but generally inner classes are better, packages are not secure (anyone can add a class to the package) public class BankAccount { double balance; // package access... }

14 Access Control - Summary PublicPackageProtectedPrivate Classes outside Package X Other class in Package XX SubclassXXX This classXXXX

15 Abstract Classes Concept same as C++, use in same types of situations (e.g., force subclasses to define behavior) Requires use of abstract keyword As in C++: –you can’t initialize objects of an abstract type. –you can initialize a variable of an abstract class with a subclass Abstract classes can include: –variables –constants –function definitions (e.g., access common variables) –function declarations (no function body) (soon we’ll learn about Interfaces, which have only constants and abstract functions (no function definitions))

16 Abstract Example abstract public class ChessPiece { private int row; private int col; // would have other fields public ChessPiece(int row, int col) { super(); this.row = row; this.col = col; } // Must be defined in subclass abstract public void move(); } public class Queen extends ChessPiece { public Queen(int row, int col) { super(row, col); } @Override public void move() { // Code here to move diagonally, horizontally, vertically }

17 Final Methods and Classes – just fyi, not covered May occasionally want to prevent others from creating subclasses or overriding methods public final class String {... } public final boolean checkPassword(String password) {... }


Download ppt "GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter."

Similar presentations


Ads by Google