Methods classes and Objects Dr Jim Burns Question
Methods, classes, and Objects Dr. Jim Burns
Question o Which of the following access modifiers is the default modifier? o public o private o protected o package
Question 2 o Which of the following access modifiers is needed to enable a class to be used without being instantiated? o Public, private, static, void, protected
Question 3 o Methods are invoked using parameters o System. out. printlin(“With raise, salary is “ + newamount); o Method headers have arguments: o Println(string[] args); o Do the parameters and arguments occupy the same locations in memory?
Question 4 o In the statement o System. out. printlin(“With raise, salary is “ + newamount); o Println(); is the method name? o What is System? o What is out?
Using Methods, classes, and Objects o Methods are similar to procedures, functions, or subroutines o Statements within a method execute only when the method is called o To execute a method, you call it from another method n “The calling method makes a method call” o Execution starts with the main method
Simple methods…. o Don’t require any data items (arguments or parameters), nor do they return any data items back o You can create any method once and use it many times in different contexts
Example Public class First { Public static void main(String[] args) { System. out. println(“First Java application”); } }
Method Declaration Is the first line or header of a method and contains Optional access modifiers The return type for the method The method name An opening parenthesis An optional list of method arguments separated by commas A closing parenthesis
Access Modifiers public – accessible anywhere private – accessible only within the class in which it is defined protected – accessible only to derived (inherited) classes only package – is the default static – does not require instantiation before it can be used and remains in place after use, without being destroyed
Implementation hiding The encapsulation of method details within a class You don’t know the algorithm being used inside the method prin. And. Inter = intr. Rate * prin + prin; prin. And. Intr = (1+intr. Rate) * prin;
Implementation hiding o We use televisions, telephones, computers, automobiles without understanding much about their internal mechanisms
Method declaration o modifiers name(arg_type arg 1, arg_type arg 2, arg_type arg 3); o HOWEVER, o modifiers name(arg_type arg 1, arg 2, arg 3); o IS INCORRECT!! o Each arg must be preceded by its own data type
Argument types… o Can be any of the primitive types o Can be any of the predefined class types o Assume a class customer exists o Public void approve. Credit(customer one. Customer);
Consider the following Public static void predict. Raise(double money. Amount) { Double new. Amount; new. Amount = money. Amount * 1. 1 System. out. println(“With raise, salary is “ + new. Amount); }
Now consider this… Public static void predict. Raise(double money. Amount) { Double new. Amount; new. Amount = money. Amount * 1. 1 System. out. println(“With raise, salary is “ + new. Amount); money. Amount = 10000; }
Would this change. . The value of salary in predict. Raise(salary); ? ? ?
No… Because Java supports passing of values rather than passing addresses, so… The values of the parameters in the calling statement are copied into the arguments of the header. The parameters and their associated arguments occupy different locations in memory C++ supports both pass-by-address and passby-value
Further, at the end of… the usage of predict. Raise(salary); the storage used by the instantiation of the method is released back, unless the method is declared static, so the assignment of 10000 to money. Amount is lost
o o o o o public class Demo. Raise { public static void main(String[] args) { double my. Salary = 200. 00; double money. Amount = 800. 00; System. out. println("Demonstrating some raises"); predict. Raise(400. 00); predict. Raise(my. Salary); predict. Raise(money. Amount); } public static void predict. Raise(double money. Amount) { double new. Amount; new. Amount = money. Amount * 1. 10; System. out. println("With raise, salary is " + new. Amount); } }
Creating Methods that Require Multiple Arguments o Public static void predict. Raise. Using. Rate(double money, double rate); o{ o double new. Amount; o new. Amount = money * (1 + rate); o System. out. println(“With raise, new salary is “ + new. Amount); o}
In the above … The order in which the paramters are passed must be consistent with the order in which the arguments are declared in the header money rate
Creating Methods that Return Values Public static double predict. Raise(double money. Amount) { double new. Amount; new. Amount = money. Amount * 1. 1; Return new. Amount; } What’s different? ? ?
This method would be invoked using… Double my. Salary; Double my. New. Salary; my. Salary = 1000; my. New. Salary = predict. Raise(my. Salary);
Could also do something like… o System. out. println(“New salary is “ + calculate. Raise(my. Salary)); o OR o Spending. Money = calculate. Raise(my. Salary) – expenses;
Learning about Class Concepts When thinking in objects, everything is an object, and every object is a member of a class Your desk is a member of the class that includes all desks and your car is a member of the class that includes all cars These are called is-a-relationships— relationships in which the object “is a” member of the class
An object… o Is an instantiation of a class (one tangible example of a class) o A Buick, a Toyota Camry, and a Volkswagon Jetta are all instantiations of the class automobile
Creating a Class Begins with a header declaration Continues with the body Data fields (instance variables) Methods Fields are named variables that you declare within a class, but outside of any method Data fields are also called instance variables
Class header declaration (one or more) An optional access modifier The keyword class Any legal identifier you choose for the name of your class Public class employee
Fields (also called ‘data fields’) o Are instance variables o Are accessible to all methods within the class o Are usually declared private o If private, they can only be accessed (read or changed) by methods within the class o This is called information hiding
Information Hiding o Class fields are declared private o Class methods are declared public o The only way another class can access a class’s fields is by use of one of its public methods
Creating Instance Methods in a Class o o o o o Public class employee { private int emp. Num; public int get. Emp. Num() { return emp. Num; } { This is an instance method that assumes emp. Num has been defined
Instance Methods o Unlike class methods, instance methods do not employ the static modifier. o Static is used for class-wide methods, but not for methods that ‘belong’ to objects o When you are creating a main method within a class, many of the methods invoked by the main will be declared static so they can be invoked without calling them from within the main
More on Instance Methods o However, if you are creating a class from which objects will be instantiated, most methods will probably be non-static because you will associate the methods with individual objects
Declaring Objects and Using their Methods Declaring a class does not create any objects A class is just an abstract description of an object Suppose a class Employee has been defined Employee some. Employee; Creates an instance of Employee
Notice in the above… o That class names will begin with a cap o Variables and instances of classes (objects) do not o Just as a convention
Declarations o int some. Value; n Complier sets aside space for some. Value (4 bytes) at compile time o Employee some. Employee; n Again, compiler is notified that you will use the identifier ‘some. Employee’ as an instance of the class Employee
Instantiations can be done as follows…. o Employee some. Employee; o some. Employee = new Employee(); Here you informed the compiler that the identifier some. Employee will be an instance of Employee and second, you told the compiler to set aside enough space for the object (instance) some. Employee at run time
This is dynamic storage allocation The actual object some. Employee does not exist until the new operator is encountered You can use Employee some. Employee = new Employee(); Here you are declaring and establishing code to create a new instance of the class Employee at the same time
Organizing Classes Public class employee { private int emp. Num; private String emp. Last. Name; private String emp. First. Name; private double emp. Salary; // Methods will go next }
The following is also equally acceptable… Public class employee { private int emp. Num; private String emp. Last. Name, emp. First. Name; private double emp. Salary; // Methods will go next }
Order. . o You can place the data and methods in any order or mix them up
Class Employee o o o o o public class Employee { private int emp. Num; private String emp. Last. Name; private String emp. First. Name; private double emp. Salary; public int get. Emp. Num() { return emp. Num; } public void set. Emp. Num(int emp) { emp. Num = emp; } public String get. Emp. Last. Name() { return emp. Last. Name; } o o o o o o public void set. Emp. Last. Name(String name) { emp. Last. Name = name; } public String get. Emp. First. Name() { return emp. First. Name; } public void set. Emp. First. Name(String name) { emp. First. Name = name; } public double get. Emp. Salary() { return emp. Salary; } public void set. Emp. Salary(double sal) { emp. Salary = sal; } }
An introduction to using Constructors Employee chauffeur = new employee(); Here you are calling a method named Employee() that is provided by default by the Java compiler It is a constructor that is provided by the compiler
Employee chauffeur = new employee(); Can also be written: o Employee chauffeur; o Chauffer = new employee(); o The first statement declares an object named ‘chauffeur’ o The second statement instantiates the object named ‘chauffeur’ o Memory is allocated when the second statement is encountered
Default constructors… Are provided by the compiler when the user does not provide one They require no arguments
When using the default constructor, it will specify the following values for data fields Numeric fields are set to 0 Character fields are set to Unicode ‘u 0000’ Boolean fields are set to false Fields that are nonprimitive objects themselves are set to null (or empty)
If you don’t like these default values, or if you want to perform additional tasks when you create an instance of a class, … o Then you must write your own constructor o Any constructor you write must have the same name as the class it constructs and constructor methods cannot have a return type
o o o o o o public class Compute. Commission { public static void main(String[] args) { char v. Type = 'S'; int value = 23000; double comm. Rate = 0. 08; compute. Commission(value, comm. Rate, v. Type); compute. Commission(40000, 0. 10, 'L'); } public static void compute. Commission(int value, double rate, char vehicle) { double commission; commission = value * rate; System. out. println("n. The " + vehicle + " type vehicle is worth $" + value); System. out. println("With " + (rate * 100) + "% commission rate, the commission is $" + commission); } }
- Slides: 49