Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Class members.

Similar presentations


Presentation on theme: "Java Class members."— Presentation transcript:

1 Java Class members

2 Write a car class that has the following fields: YearModel (int filed hold the car’s year model), Make (string field that hold the make of the car), and Speed (int field that holds car’s current speed). The class has the following methods: constructor that accepts the car’s year model and make arguments and assign speed to 0, assign_data ( ) to set values for all fields of the class by user, accelerate ( ) which add 5 to the speed each time it is called, break () which subtract 5 from speed each time it is called, and display () to print out the car’s information. Create two objects from this class and call accelerate and break methods five time for each and display the speed each time.

3 local variables :that are declared but not initialized will not be set to a default by the compiler
Accessing an uninitialized local variable will result in a compile-time error QUESTION? What is the result of attempting to compile and run method m? A. Prints: Hello 0 B. Compilation fails. C. Runtime Error. D. Prints: Hello . class Test { void m() int i; System.out.println("Hello "+i); } C:\Documents and Settings\Alex Computer\My Documents\Test.java:7: variable i might not have been initialized System.out.println("Hello "+i); ^ 1 error Answer: B

4 Methods class Bicycle { int speed; static int numberOfBicycles;
Instance Methods (Non-static methods) Class Methods (static methods) class Bicycle { int speed; static int numberOfBicycles; void speedUp(int increment) speed += increment; } static void m() …. Instance method the currentSpeed of one bicycle is independent from the currentSpeed of another. . A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. Class method

5 Members of a class Static Members Non Static Members
Non Static variables Non Static methods Static variables Static methods

6 Instance Variables Instance variables store the data about objects
Each object has its own copy of instance variables with its own values. class A { int x; int y; } a1 a2 x=9 y=12 x=2 y=4

7 Static Class members: Static variables
class Student{ static String dean; String name; int registrationNumber; Student( String studentName , int regNumber) { name=studentName; registrationNumber=regNumber; } Static variables (class Variables) Ex: static int x; Only one copy of this variable exist, all objects share the same copy with the same value. Can be accessed without creation of any object. Can be accessed in same class by variableName or classname.varaibleName or ObjectName.variableName. Can be accessed in another class by classname.varaibleName or ObjectName.variableName. class Test{ public static void main (String [] arg) { Student student1=new Student("Ahmed Aly", 123); Student student2=new Student("Akram ahmed", 367); Student.dean="Dr Mohamed"; System.out.println(student1.dean); System.out.println(student2.dean); }} Local Variables can never be declared static.

8 Example class A{ static int x; int y; } x 2 3 1 y=0 y=1 class Test {
public static void main (String [] arg) A.x++; A a1=new A(); a1.x++; a1.y++; A a2=new A(); a2.x++; a2.y++; } a1 y=2 y=0 y=0 a2

9 Static Class members :Static methods
class Student{ static String deanName; String name; int registrationNumber; Student( String studentName , int regNumber){ name=studentName; registrationNumber=regNumber; } public static void setDeanName(String name) { deanName=name; Static methods Ex: static void m(){} Can be called without creation of any object Can only access static variables and only call static methods. Can be called in same class by methodName() or classname.methodName() or ObjectName.methodName() (same effect) Can be called in another class by classname.methodName() or ObjectName.methodName() class Test{ public static void main (String [] arg){ Student student1=new Student("Ahmed Aly", 123); Student student2=new Student("Akram ahmed", 367); Student.setDeanName("Dr Mohamed"); }} How do you decide whether a variable or method should be an instance one or a static one? A variable or method that is dependent on a specific instance of the class should be an instance variable or method. A variable or method that is not dependent on a specific instance of the class should be a static variable or method. For example, every circle has its own radius. Radius is dependent on a specific circle. Therefore, radius is an instance variable of the Circle class. Since the getArea method is dependent on a specific circle, it is an instance method. None of the methods in the Math class, such as random, pow, sin, and cos, is dependent on a specific instance. Therefore, these methods are static methods. The main method is static, and can be invoked directly from a class. access modifiers and static keyword can appear in any order

10 class Car { String name; int model; int weight; String color; void start(){……} void drive(){……} void brake(){……} }

11 Abstraction Abstractions is formed by reducing the information content of a concept typically to retain only information which is relevant for a particular purpose Abstraction design : abstraction reduce and factor out details so that one can focus on a few concepts. Abstraction allows the design stage to be separated from the implementation stage of the software development. class Person{ String name; Date birth; …. boolean isAdult() {….} } class Course{ String code; int numOfStudents; …. boolean isFull() {….} } abstraction: A distancing between ideas and details. You understand its external behavior (buttons, screen, etc.) You DON'T understand its inner workings, nor do you need to. Specifying what an object can do without specifying how it does it is an abstraction.

12 Example 1 : Abstraction of a Credit Card
public class CreditCard{ double limit; int number; double balance; static final double MAX_LIMIT=20000; public CreditCard(int number){ this.number=number; } public void setLimit(double limit){ If(limit<=MAX_LIMIT) this.limit=limit; else return; public boolean buyWithCredit(double amount){ if ((balance+amount)>limit) return false; balance=balance+amount; return true;} public void creditSettle(double amount){ balance=balance-amount; Misuse of class class Test{ public static void main (String [] arg){ CreditCard card1=new CreditCard(345); card1.setLimit(5000); card1.buyWithCredit(500); card1.buyWithCredit(1500); card1.limit=100000; card1.buyWithCredit(15000); }

13 Encapsulation A language construct that facilitates the bundling of data with the methods operating on that data (this is achieved using the class structure) A language mechanism for restricting access to some of the object's components, (this is achieved using access modifiers) A class should encapsulate only one idea , i.e. a class should be cohesive Your Encapsulation design should minimize dependency in order to ensure that there is a loose-coupling class AutoTransmission { private int valves; void shiftGear() {……………….} } The class is the mechanism by which encapsulation is achieved in Java. the internal representation of an object is generally hidden from view outside of the object's definition. Typically, only the object's own methods can directly inspect or manipulate its fields

14 Better Encapsulation of class CreditCard
public class CreditCard{ private double limit; private int number; private double balance; public static double fimal MAX_LIMIT=2000; public CreditCard(int number){ this.number=number; } public void setLimit(double limit){ If(limit<=MAX_LIMIT) this.limit=limit; else return; public boolean buyWithCredit(double amount){ if ((balance+amount)>limit) return false; balance=balance+amount; return true; public void creditSettle(double amount){ balance=balance-amount; }} class Test{ public static void main (String [] arg){ CreditCard card1=new CreditCard(345); card1.setLimit(5000); card1.buyWithCredit(500); card1.buyWithCredit(1500); card1.limit=100000; Card1.setLimit(100000); card1.buyWithCredit(15000);//return false }

15 Encapsulation

16 Data Field Encapsulation
Instance variables are declared private to prevent misuse. providing methods that can be used to read/write the state rather than accessing the state directly. public class Person{ private int age; public void setAge(int age ){ if (age<0) { System.out.println("unaccepted value"); return; } this.age=age; public int getAge(){ return age; Person p1=new Person(); p1.age=10; System.out.println(p1.age); Person p1=new Person(); p1.setAge(10); To prevent data from being tampered with and to make the class easy to maintain, most of the data fields in this book will be private.

17 Accessors and mutators
Data Field Encapsulation public class Person{ private int age; private String name; private boolean adult; public int getAge() {return age;} public void setAge(int age ) {this.age=age;} public String getName() {return name;} public void setName(String name) {this.name=name;} public boolean isAdult() {return adult;} public void setAdult(boolean adult) {this.adult=adult;} } Instance variables are declared private to prevent misuse. providing methods that can be used to read/write the state rather than accessing the state directly. Accessors and mutators Accessor method (getters): a method that provides access to the state of an object to be accessed. A get method signature: public returnType getPropertyName() If the returnType is boolean : public boolean isPropertyName() Mutator method(setters): a method that modifies an object's state. A set method signature: public void setPropertyName(dataType propertyValue) To prevent data from being tampered with and to make the class easy to maintain, most of the data fields in this book will be private.

18 public class GasTank { private double amount = 0; public void addGas ( double doubleAmount) { amount += doubleAmount; } public void useGas ( double doubleAmount) amount -= doubleAmount; } public double getGasLevel () { return amount;

19 Example 2 :Class MusicAlbum
Implement Class MusicAlbum which encapsulated a music Album, each album has a string variable albumTitle and a String variable singer representing the name of singer, double variable price representing the price of album, objects of this class are Initialized using all of its instance variables. The class has accessor methods for all its Variables and a mutator method for price

20 public class MusicAlbum { private String albumTitle;
private String singer; private double price; Public MusicAlbum(String albumTitle, String singer, double price) { this.albumTitle=albumTitle; this.singer=singer; this.price=price; } public String getAlbumTitle() return albumTitle; public String getSinger() return singer; public double getPrice() { return price; } public void setPrice ( double price) this .price=price;

21 public class Car { private String make, model; private int year; public Car(String make, String model, int year) { setMake(make); setModel(model); setYear(year); } public String getMake() {return make;} public void setMake(String make) {this.make = make;} public String getModel() {return model;} public void setModel(String model) {this. model = model;} public int getYear() {return year;} public void setYear(int year){this.year=year;}

22 Elevator Case Study

23 Abstraction of Elevator
public class Elevator { public boolean doorOpen = false; public int currentFloor = 0; public int weight = 0; public final int CAPACITY = 1000; public final int TOP_FLOOR = 5; public final int BOTTOM_FLOOR = 0; }

24 Improper use of class Elevator
public class PublicElevatorTest { public static void main(String[] args) { Elevator pubElevator = new Elevator(); pubElevator.doorOpen = true; // passengers get on pubElevator.doorOpen = false; // doors close // go down to floor -1 (below bottom of building) pubElevator.currentFloor--; pubElevator.currentFloor++; // jump to floor 7 (floor 7 does not exist!!) pubElevator.currentFloor = 7; pubElevator.doorOpen = true; // passengers get on/off pubElevator.doorOpen = false; pubElevator.currentFloor = 1; // go to the first floor pubElevator.currentFloor++; // elevator moves w/ door open }

25 Comment on first design
Because the PublicElevator class does not use  encapsulation, the PublicElevatorTest class can change the  values of its attributes freely and in many undesirable ways.   For example, on statement after // go down to floor  , which might not be a valid floor.   Also, on the statement, pubElevator.currentFloor = 7,  the currentFloor attribute is set to 7 that, according to the TOP_FLOOR constant, is an invalid floor

26 Encapsulation Elevator
public class Elevator { private boolean doorOpen = false; private int currentFloor = 0; private int weight = 0; public final int CAPACITY = 1000; public final int TOP_FLOOR = 5; public final int BOTTOM_FLOOR = 0; }

27 public class PrivateElevator1Test {
public static void main(String[] args) { Elevator priElevator = new Elevator(); /* * The following lines of code will not compile * because they attempt to access private variables. */ priElevator.doorOpen = true; // passengers get on priElevator.doorOpen = false; // doors close // go down to floor -1 (below bottom of building) priElevator.currentFloor--; priElevator.currentFloor++; // jump to floor 7 (only 5 floors in building) priElevator.currentFloor = 7; priElevator.doorOpen = true; // passengers get on/off priElevator.doorOpen = false; priElevator.currentFloor = 1; // go to the first floor priElevator.currentFloor++; // elevator moves w/ door open }

28 Comment on second design
The code does not compile because the main method in  the  PrivateElevator1Test class is attempting to change the value of private attributes in the PrivateElevator1 class.  The PrivateElevator1 class is not very useful, however,  because there is no way to modify the values of the class. In an ideal program, most or all the attributes of a class are kept private.   Private attributes cannot be modified or viewed directly by classes outside their own class, they can only be modified or viewed by methods of that class.  These methods should contain code and business logic to make sure that inappropriate values are not assigned to the variable or an attribute. 

29 Better Encapsulation of class Elevator
public class Elevator { private boolean doorOpen = false; private int currentFloor = 0; private int weight = 0; public final int CAPACITY = 1000; public final int TOP_FLOOR = 5; public final int BOTTOM_FLOOR = 0; public void openDoor() { doorOpen = true; } public void closeDoor() { calculateWeight(); if (weight <= CAPACITY) { doorOpen = false; } else { System.out.println("The elevator has exceeded capacity."); System.out.println("Doors will remain open until someone exits!");

30 // random weight for simulation
private void calculateWeight() { weight = (int)(Math.random() * 1500); System.out.println("The weight is " + weight); } public void goUp() { if (!doorOpen) { if (currentFloor < TOP_FLOOR) { currentFloor++; System.out.println(currentFloor); } else { System.out.println("Already on top floor."); System.out.println("Doors still open!");

31 public void goDown() { if (!doorOpen) { if (currentFloor > BOTTOM_FLOOR) { currentFloor--; System.out.println(currentFloor); } else { System.out.println("Already on bottom floor."); } System.out.println("Doors still open!");

32 public void setFloor(int desiredFloor) {
if ((desiredFloor >= BOTTOM_FLOOR) && (desiredFloor <= TOP_FLOOR)) { while (currentFloor != desiredFloor) { if (currentFloor < desiredFloor) { goUp(); } else { goDown(); } System.out.println("Invalid Floor"); public int getFloor() { return currentFloor; public boolean getDoorStatus() { return doorOpen;

33 // PrivateElevator2Test.java public class PrivateElevator2Test {
public static void main(String[] args) { Elevator privElevator = new Elevator(); privElevator.openDoor(); privElevator.closeDoor(); privElevator.goDown(); privElevator.goUp(); int curFloor = privElevator.getFloor(); if (curFloor != 5 && !privElevator.getDoorStatus()) { privElevator.setFloor(5); } privElevator.setFloor(10); }} privElevator.getClass();

34 Comment on third design
Because the PrivateElevator2 class does not allow direct  manipulation of the attributes of the class, the PrivateElevator2Test class can only invoke methods to act on the attribute variables of the class.   These methods perform checks to verify that the correct values are used before completing a task, ensuring that the elevator does not do  anything unexpected.  All of the complex logic in this program is encapsulated within the  public method of the PrivateElevator2 class.  The code in the test class is, therefore, easy to read and maintain.  This concept is one of the many benefits of encapsulation.

35 Example : Abstraction of a Product
: private +:public # :protected Add a default empty no-arg constructor to initalize member variables Add a constructor for instance variable initialization using arguments

36 public class Product { private String code; private String description; private double price; public Product() code = ""; description = ""; price = 0; } public Product(String code, String description, double price) this.code = code; this.description = description; this.price = price;

37 public void setCode(String code)
{ this.code = code; } public String getCode(){ return code; public void setDescription(String description) this.description = description; public String getDescription() return description; public void setPrice(double price) { this.price = price; } public double getPrice() return price;

38 Creating Object of class Product

39 class Test{ public static void main (String [] arg){ Product product1=new Product(); product1.setCode("Java"); product1.setDescription("Begining Java 2"); product1.setPrice(49.5 ); Product product2=new Product("mcb2","MainFrame Cobol",59.50); displayProduct(product1); displayProduct(product2); } public static void displayProduct(Product product) { String productCode=product.getCode(); String productDescription=product.getDescription(); double productPrice=product.getPrice(); System.out.println("Product code is " +productCode + ", description :"+ productDescription + ", price "+productPrice);

40 Access Control Java provides several modifiers that control access to data fields, methods, and classes public makes classes, methods, and data fields accessible from any class. private makes methods and data fields accessible only from within its own class. If no access modifier is used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-access. If protected is used, then that member can be accessed by own class and classes from same package and from subclass outside the package . public int i; private double j; public void m (){} int x; C# -The following five accessibility levels can be specified using the access modifiers:    public   protected   internal   internal protected   private -the default of a class or interface is internal , foe a member is private The default constructor has the same access as its class Local Variables can not have an access modifier

41 The Different Levels of Access Control
private default protected public Visibility From the same class From any class in the same package From any class outside the package From a subclass in the same package From a subclass outside the same package Yes Yes Yes Yes Yes Yes Yes No No Yes No No Yes Yes Yes No Yes Yes No No Access modifiers apply to class members (variables and methods) and constructors too. Class D,E subclasses of class C

42 Designing the Loan Class
TestLoan

43 Class Loan public class Loan { private double annualInterestRate;
private int numberOfYears; private double loanAmount; private java.util.Date loanDate; /** Default constructor */ public Loan() { this(2.5, 1, 1000); } /** Construct a loan with specified annual interest rate, number of years and loan amount */ public Loan(double annualInterestRate, int numberOfYears, double loanAmount) { this.annualInterestRate = annualInterestRate; this.numberOfYears = numberOfYears; this.loanAmount = loanAmount; loanDate = new java.util.Date(); }

44 Class Loan…… /** Return annualInterestRate */
public double getAnnualInterestRate() { return annualInterestRate; } /** Set a new annualInterestRate */ public void setAnnualInterestRate(double annualInterestRate) { this.annualInterestRate = annualInterestRate; } /** Return numberOfYears */ public int getNumberOfYears() { return numberOfYears; } /** Set a new numberOfYears */ public void setNumberOfYears(int numberOfYears) { this.numberOfYears = numberOfYears; } /** Return loanAmount */ public double getLoanAmount() { return loanAmount; }

45 Class Loan…… /** Set a newloanAmount */
public void setLoanAmount(double loanAmount) { this.loanAmount = loanAmount; } /** Find monthly payment */ public double getMonthlyPayment() { double monthlyInterestRate = annualInterestRate / 1200; double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12))); return monthlyPayment; } /** Find total payment */ public double getTotalPayment() { double totalPayment = getMonthlyPayment() * numberOfYears * 12; return totalPayment; } /** Return loan date */ public java.util.Date getLoanDate() { return loanDate; }

46 Class TestLoan import java.util.Scanner; public class TestLoan {
/** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Enter yearly interest rate System.out.print( "Enter yearly interest rate, for example, 8.25: "); double annualInterestRate = input.nextDouble(); // Enter number of years System.out.print("Enter number of years as an integer: "); int numberOfYears = input.nextInt(); // Enter loan amount System.out.print("Enter loan amount, for example, : "); double loanAmount = input.nextDouble();

47 Class TestLoan………….. // Create Loan object Loan loan =
new Loan(annualInterestRate, numberOfYears, loanAmount); // Display loan date, monthly payment, and total payment System.out.printf("The loan was created on %s\n" + "The monthly payment is %.2f\nThe total payment is %.2f\n", loan.getLoanDate().toString(), loan.getMonthlyPayment(), loan.getTotalPayment()); } Hint: printf works the same as in C programming language Method toString() in class java.util.Date returns a string representation of the date object

48 The BMI Class BMI UseBMIClass Run

49 Intro to OOP with Java, C. Thomas Wu
Code Directory: BMI Calculator Source Files: BMI.java UseBMI.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc.

50 Case Study: Stack Design a java class that encapsulate the data structure Stack ( Last in First out). The class has 2 methods (push) : method for adding items to stack, the push operation adds items to the top of the list (pop) :method for retrieving items from the stack, . The pop operation removes an item from the top of the list, and returns its value to the caller. in the case of overflow the user should be informed with a message in the case of underflow, the user should be informed with a message & a value of zero is returned. Assumptions : The stack will hold up to 10 +ve integer values.

51 Class Stack /* This class defines an integer stack that can hold 10 values*/ class Stack { private int stck[] = new int[10]; private int tos; Stack() { tos = -1; } // Push an item onto the stack public void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; // Pop an item from the stack public int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--];

52 public static void main(String args[]) { int element;
class TestStack { public static void main(String args[]) { int element; Stack mystack1 = new Stack(); // push some numbers onto the stack mystack1.push(1); mystack1.push(17); //mystack1.stck[3]=4 compile error call is encapsulated stck is private mystack1.push(20); // pop some numbers off the stack element=mystack1.pop(); System.out.println("Element is "+element); } Without enapsulation Stack class. for the array that holds the stack, stck, to be altered by code outside of the Stack class. ex mystack1.stck[3]=4; This leaves Stack open to misuse (encaspulation not met)

53 Example Write OOP program to include Employee class to store employee’s name, hourly rate, brith_date, start_date, and hours worked. Brith_date and start_date are object of Date class (day, month, year). Employee class has methods: initialize hourly rate to a minimum wage of $6.00 per hour and hours worked to 0 when employee object is defined Method to get employee’s name, hourly rate, and hours worked from user Method to return weekly pay including overtime pay where overtime is paid at rate of time-and-a-half for any hours worked over 40 Method to display employee information including employee pay for given week

54 Example Define a person class with members: ID, name, address, and telephone number. The class methods are change_data( ), get_data( ), and display_data( ). Declare objects table with size N and provide the user to fill the table with data. Allow the user to enter certain ID for the Main class to display the corresponding person's name, address, and telephone number.

55 A chess club wants to make the rating list of the members of the club
A chess club wants to make the rating list of the members of the club. When two members play a game, when a member plays with someone not belonging to club, his/her rating does not change: The rating of a new player is always When a player wins, his/her rating is increased by 10 points. When a player loses, his/her rating is decreased by 10 points. If a game is a draw (neither of the players wins), the rating of the player having originally higher rating is decreased by 5 points and the rating of the player having originally lower rating is increased by 5 points. If the ratings of the players are originally equal, they are not changed. The rating can never be negative. If the rating would become negative according to the rules above, it is changed to 0. Write a class Chessplayer that have instance variables name (String), count (int) and rating (int). The variable count is used to save the number of the games the player has played with other members of the club. A new player has a count value 0. Write a constructor to create a new player and the following methods (the headers of the methods show the purpose and parameters of the methods): String returnName(), void changeName(String newName), int returnCount(), void setCount(int newCount), int returnRating(), void setRating(int newRating), String toString() to help to output information about players, void game(Chessplayer anotherPlayer, int result). The method game changes the ratings and counts of both players according to the rules given above. The second parameter of the method tells the result of the game. If the parameter has value -1, anotherPlayer has won, if the parameter has value 1, anotherPlayer has lost, if the parameter has value 0, the game was a draw.

56 Write a class WaterTank to describe water tanks
Write a class WaterTank to describe water tanks. Each water tank can contain a certain amount of water which has a certain temperature. The temperature must be more than 0, but less than 100. The class have variables volume (double) the volume of the tank, temperature (double) the temperature of the water in tank, and quantity (double) the quantity of water in tank. Write a constructor which has three parameters: the volume of the water tank to be created, the amount of water in it and the temperature of the water. (If the amount of the water is greater than the volume, the quantity of water is set to the volume of the tank. If the temperature is not in the given bounds, the temperature is set to 20) Write also the following methods: double getQuantity() returns the amount of water in the tank void setTemperature(double newTemperature) changes the temperature of water according to the parameter. If the parameter is not between 0 and 100, the temperature is not changed. double transferWater(WaterTank anotherTank) transfers as much water as possible from the tank given as the first parameter to this tank. (The limit is either the amount of water in the other tank or the space available in this tank.) The method changes the values of the variables quantity and temperature of this tank and the value of variable quantity of the other tank. The return value of the method tells the amount of water transferred. String toString() returns a string containing information of this tank. Use the following expression to calculate the new temperature of water after some water has been added: if V1 liters of water having temperature T1 (in Centigrades) is combined with V2 liters of water having temperature T2, the temperature of the water after that is about (V1*T1 + V2*T2) / (V1 + V2). In addition, write a main program which creates three water tanks, changes the temperature of water in one of them, and transfers water from one tank to another tank. In the end, the program outputs information about all tanks.


Download ppt "Java Class members."

Similar presentations


Ads by Google