Java Class members 1 Write a car class
Java Class members 1
• Write a car class that has the following fields: Year. Model (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. 2
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? class Test { void m() { int i; System. out. println("Hello "+i); } } Answer: B 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. C: Documents and SettingsAlex ComputerMy DocumentsTest. java: 7: variable i might not have been initialized System. out. println("Hello "+i); ^ 1 error 3
Methods Instance Methods (Non-static methods) Instance method Class Methods (static methods) class Bicycle { int speed; static int number. Of. Bicycles; void speed. Up(int increment) { speed += increment; } static void m() { …. } } 4
Members of a class Static Members Static variables Static methods Non Static Members Non Static variables Non Static methods 5
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; … } a 2 a 1 x=9 y=12 x=2 y=4 6
Static Class members: 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 variable. Name or classname. varaible. Name or Object. Name. variable. Name. Ø Can be accessed in another class by classname. varaible. Name or Object. Name. variable. Name. Local Variables can never be declared static. class Student{ static String dean; String name; int registration. Number; Student( String student. Name , int reg. Number) { name=student. Name; registration. Number=reg. Number; } } class Test{ public static void main (String [] arg) { Student student 1=new Student("Ahmed Aly", 123); Student student 2=new Student("Akram ahmed", 367); Student. dean="Dr Mohamed"; System. out. println(student 1. dean); System. out. println(student 2. dean); }} 7
Example x 1 3 2 y=0 y=1 a 1 y=2 y=0 a 2 class A{ static int x; int y; } class Test { public static void main (String [] arg) { A. x++; A a 1=new A(); a 1. x++; a 1. y++; A a 2=new A(); a 2. x++; a 2. y++; } } 8
Static Class members : 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 method. Name() or classname. method. Name() or Object. Name. method. Name() (same effect) ØCan be called in another class by classname. method. Name() or Object. Name. method. Name() (same effect) access modifiers and static keyword can appear in any order class Student{ static String dean. Name; String name; int registration. Number; Student( String student. Name , int reg. Number){ name=student. Name; registration. Number=reg. Number; } public static void set. Dean. Name(String name) { dean. Name=name; } } class Test{ public static void main (String [] arg){ Student student 1=new Student("Ahmed Aly", 123); Student student 2=new Student("Akram ahmed", 367); Student. set. Dean. Name("Dr Mohamed"); 9 }}
class Car { String name; int model; int weight; String color; void start(){……} void drive(){……} void brake(){……} } 10
Encapsulation I. A language construct that facilitates the bundling of data with the methods operating on that data (this is achieved using the class structure) II. 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 Auto. Transmission { private int valves; void shift. Gear() {………………. } } 11
Encapsulation 12
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. Person p 1=new Person(); p 1. age=10; System. out. println(p 1. age); Person p 1=new Person(); p 1. set. Age(10); 13 public class Person{ private int age; public void set. Age(int age ){ if (age<0) { System. out. println("unaccepted value"); return; } this. age=age; } public int get. Age(){ return age; } }
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. 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 return. Type get. Property. Name() If the return. Type is boolean : public boolean is. Property. Name() • Mutator method(setters): a method that modifies an object's state. A set method signature: public void set. Property. Name(data. Type property. Value) 14 public class Person{ private int age; private String name; private boolean adult; public int get. Age() {return age; } public void set. Age(int age ) {this. age=age; } public String get. Name() {return name; } public void set. Name(String name) {this. name=name; } public boolean is. Adult() {return adult; } public void set. Adult(boolean adult) {this. adult=adult; } }
public class Gas. Tank { private double amount = 0; public void add. Gas ( double. Amount) { amount += double. Amount; } public void use. Gas ( double. Amount) { amount -= double. Amount; } public double get. Gas. Level () { return amount; } } 15
Example 2 : Class Music. Album Implement Class Music. Album which encapsulated a music Album, each album has a string variable album. Title 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 16
public class Music. Album { private String album. Title; private String singer; private double price; Public Music. Album(String album. Title, String singer, double price) { this. album. Title=album. Title; this. singer=singer; this. price=price; } public double get. Price() { return price; } public void set. Price ( double price) { } } this. price=price; public String get. Album. Title() { return album. Title; } public String get. Singer() { return singer; } 17
public class Car { private String make, model; private int year; public Car(String make, String model, int year) { set. Make(make); set. Model(model); set. Year(year); } public String get. Make() {return make; } public void set. Make(String make) {this. make = make; } public String get. Model() {return model; } public void set. Model(String model) {this. model = model; } public int get. Year() {return year; } public void set. Year(int year){this. year=year; } } 18
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 19
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; } 20
public void set. Code(String code) { this. code = code; } public void set. Price(double price) { this. price = price; } public String get. Code(){ return code; } public double get. Price() { return price; } public void set. Description(String description) { this. description = description; } } public String get. Description() { return description; } 21
Creating Object of class Product 22
class Test{ public static void main (String [] arg){ Product product 1=new Product(); product 1. set. Code("Java"); product 1. set. Description("Begining Java 2"); product 1. set. Price(49. 5 ); Product product 2=new Product("mcb 2", "Main. Frame Cobol", 59. 50); display. Product(product 1); display. Product(product 2); } public static void display. Product(Product product) { String product. Code=product. get. Code(); String product. Description=product. get. Description(); double product. Price=product. get. Price(); System. out. println("Product code is " +product. Code + ", description : "+ product. Description + ", price "+product. Price); } } 23
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; The default constructor has the same access as its class Local Variables can not have an access modifier 24
The Different Levels of Access Control Visibility public protected default Yes From the same class Yes From any class in the same package Yes From any class outside the package Yes From a subclass in the same package From a subclass outside the same package private Yes No No Yes Yes Yes No No No Access modifiers apply to class members (variables and methods) and constructors too. Class D, E subclasses of class C 25
Designing the Loan Class Loan Test. Loan 26
Class Loan public class Loan { private double annual. Interest. Rate; private int number. Of. Years; private double loan. Amount; private java. util. Date loan. Date; /** 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 annual. Interest. Rate, int number. Of. Years, double loan. Amount) { this. annual. Interest. Rate = annual. Interest. Rate; this. number. Of. Years = number. Of. Years; this. loan. Amount = loan. Amount; loan. Date = new java. util. Date(); } 27
Class Loan…… /** Return annual. Interest. Rate */ public double get. Annual. Interest. Rate() { return annual. Interest. Rate; } /** Set a new annual. Interest. Rate */ public void set. Annual. Interest. Rate(double annual. Interest. Rate) { this. annual. Interest. Rate = annual. Interest. Rate; } /** Return number. Of. Years */ public int get. Number. Of. Years() { return number. Of. Years; } /** Set a new number. Of. Years */ public void set. Number. Of. Years(int number. Of. Years) { this. number. Of. Years = number. Of. Years; } /** Return loan. Amount */ public double get. Loan. Amount() { return loan. Amount; } 28
Class Loan…… /** Set a newloan. Amount */ public void set. Loan. Amount(double loan. Amount) { this. loan. Amount = loan. Amount; } /** Find monthly payment */ public double get. Monthly. Payment() { double monthly. Interest. Rate = annual. Interest. Rate / 1200; double monthly. Payment = loan. Amount * monthly. Interest. Rate / (1 - (Math. pow(1 / (1 + monthly. Interest. Rate), number. Of. Years * 12))); return monthly. Payment; } /** Find total payment */ public double get. Total. Payment() { double total. Payment = get. Monthly. Payment() * number. Of. Years * 12; return total. Payment; } /** Return loan date */ public java. util. Date get. Loan. Date() { return loan. Date; } } 29
import java. util. Scanner; Class Test. Loan public class Test. Loan { /** Main method */ public static void main(String[] args) { // Create a Scanner input = new Scanner(System. in); // Enter yearly interest rate System. out. print( "Enter yearly interest rate, for example, 8. 25: "); double annual. Interest. Rate = input. next. Double(); // Enter number of years System. out. print("Enter number of years as an integer: "); int number. Of. Years = input. next. Int(); // Enter loan amount System. out. print("Enter loan amount, for example, 120000. 95: "); double loan. Amount = input. next. Double(); 30
Class Test. Loan…………. . // Create Loan object Loan loan = new Loan(annual. Interest. Rate, number. Of. Years, loan. Amount); } } // Display loan date, monthly payment, and total payment System. out. printf("The loan was created on %sn" + "The monthly payment is %. 2 fn. The total payment is %. 2 fn", loan. get. Loan. Date(). to. String(), loan. get. Monthly. Payment(), loan. get. Total. Payment()); Hint: Ø printf works the same as in C programming language Ø Method to. String() in class java. util. Date returns a string representation of the date object 31
Case Study: Stack Design a java class that encapsulate the data structure Stack ( Last in First out). q. 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. qin the case of overflow the user should be informed with a message qin 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. 32
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--]; } } 33
class Test. Stack { public static void main(String args[]) { int element; Stack mystack 1 = new Stack(); } } // push some numbers onto the stack mystack 1. push(1); mystack 1. push(17); //mystack 1. stck[3]=4 compile error call is encapsulated stck is private mystack 1. push(20); // pop some numbers off the stack element=mystack 1. pop(); System. out. println("Element is "+element); 34
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
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. 36
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 return. Name(), void change. Name(String new. Name), int return. Count(), void set. Count(int new. Count), int return. Rating(), void set. Rating(int new. Rating), String to. String() to help to output information about players, void game(Chessplayer another. Player, 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, another. Player has won, if the parameter has value 1, another. Player has lost, if the parameter has value 0, the game was a draw.
Write a class Water. Tank 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 get. Quantity() returns the amount of water in the tank void set. Temperature(double new. Temperature) changes the temperature of water according to the parameter. If the parameter is not between 0 and 100, the temperature is not changed. double transfer. Water(Water. Tank another. Tank) 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 to. String() 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 V 1 liters of water having temperature T 1 (in Centigrades) is combined with V 2 liters of water having temperature T 2, the temperature of the water after that is about (V 1*T 1 + V 2*T 2) / (V 1 + V 2). 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.
- Slides: 38