1 / 38

Java

Java. Class members. 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).

tdeleon
Download Presentation

Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 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 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; … } a2 a1 x=2 y=4 x=9 y=12

  7. Static Class members: Static variables class Student{ static String dean; String name; intregistrationNumber; Student( String studentName , intregNumber) { 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.varaibleNameor 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("Akramahmed", 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{ staticint x; int y; } x 1 2 3 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++; a2.y++; } } a1 y=0 y=0 y=2 a2

  9. Static Class members :Static methods class Student{ static String deanName; String name; intregistrationNumber; Student( String studentName , intregNumber){ 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() • (same effect) class Test{ public static void main (String [] arg){ Student student1=new Student("Ahmed Aly", 123); Student student2=new Student("Akramahmed", 367); Student.setDeanName("Dr Mohamed"); }} 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. 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() {……………….} }

  12. Encapsulation

  13. 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);

  14. Data Field Encapsulation Accessors and mutators public class Person{ private int age; private String name; private boolean adult; public intgetAge() {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. • Accessor method (getters): a method that provides access to the state of an object to be accessed. A get method signature: public returnTypegetPropertyName() If the returnType is boolean : public booleanisPropertyName() • Mutator method(setters): a method that modifies an object's state. A set method signature: public void setPropertyName(dataTypepropertyValue)

  15. 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; } }

  16. 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

  17. 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; } }

  18. 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;} }

  19. 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

  20. 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; }

  21. 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; } }

  22. Creating Object of class Product

  23. 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); } }

  24. 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 protectedis used, then that member can be accessed by own class and classes from samepackage and from subclass outside the package . publicinti; private double j; public void m (){} int x; The default constructor has the same access as its class Local Variables can not have an access modifier

  25. The Different Levels of Access Control 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

  26. Designing the Loan Class Loan TestLoan

  27. Class Loan publicclassLoan { privatedoubleannualInterestRate; privateintnumberOfYears; privatedoubleloanAmount; privatejava.util.DateloanDate; /** 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, intnumberOfYears, double loanAmount) { this.annualInterestRate = annualInterestRate; this.numberOfYears= numberOfYears; this.loanAmount= loanAmount; loanDate= newjava.util.Date(); }

  28. Class Loan…… /** Return annualInterestRate */ public double getAnnualInterestRate() { return annualInterestRate; } /** Set a new annualInterestRate */ publicvoid 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; }

  29. Class Loan…… /** Set a newloanAmount*/ public void setLoanAmount(double loanAmount) { this.loanAmount= loanAmount; } /** Find monthly payment */ public double getMonthlyPayment() { doublemonthlyInterestRate = annualInterestRate / 1200; doublemonthlyPayment = loanAmount * monthlyInterestRate / (1 - (Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12))); returnmonthlyPayment; } /** Find total payment */ public double getTotalPayment() { doubletotalPayment = getMonthlyPayment() * numberOfYears * 12; returntotalPayment; } /** Return loan date */ public java.util.DategetLoanDate() { returnloanDate; } }

  30. 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, 120000.95: "); double loanAmount = input.nextDouble();

  31. 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

  32. 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.

  33. Class Stack /* This class defines an integer stack that can hold 10 values*/ class Stack { privateintstck[] = new int[10]; privateinttos; 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--]; } }

  34. 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); element=mystack1.pop(); System.out.println("Element is "+element); } }

  35. 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

  36. 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.

  37. 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 1000. 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.

  38. 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.

More Related