• No results found

Access Specifiers, Constructors and Methods Methods

In document Core Java Handout v1.0 (Page 145-164)

Learning Objectives

After completing this session, you will be able to:

‰ Identify constructors and the different types of method declaration

Constructors

‰ Java provides a special construct named constructor exclusively for creating an object of a class and initializing its instance variables.

‰ Constructors should have the same name as the name of the class.

‰ It is generally declared as public.

‰ It may have optional list of arguments.

‰ It does not have any return type and not even void.

‰ You cannot invoke a constructor on an existing object.

‰ You can use a constructor only in combination with the new operator.

To declare a constructor, you write,

<modifier> <className> (<parameter>*) { <statement>*

}

Default Constructor (Method)

The default constructor (no-arg constructor):

‰ Constructor without any parameters

‰ If the class does not specify any constructors, then an implicit default constructor is created

Example: Default Constructor Method of StudentRecord Class public StudentRecord()

{

//some code here }

Overloading Constructor Methods public StudentRecord()

//some initialization code here }

public StudentRecord(String temp) { this.name = temp;

}

public StudentRecord(String name, String address { this.name = name;

this.address = address;

}

public StudentRecord(double mGrade, double eGrade, double sGrade) {

mathGrade = mGrade;

englishGrade = eGrade;

scienceGrade = sGrade;

}

Applying Constructors

To apply these constructors, you have the following code:

public static void main( String[] args ){

//create three objects for Student record

StudentRecord annaRecord=new StudentRecord("Anna");

StudentRecord beahRecord=new StudentRecord("Beah", "Philippines");

StudentRecord crisRecord=new

StudentRecord(80,90,100);

//some code here }

“this()” Constructor Call

‰ Constructor calls can be chained, which means that you can call another constructor from inside another constructor.

‰ You use the this() method call for this.

‰ There are a few things to remember when using the this() method constructor call:

‰ When using this constructor call, it must occur as the first statement in a constructor.

‰ It can only be used in a constructor definition. The this call can then be followed by any other relevant statements.

Example of “this()” Constructor Call 1: public StudentRecord(){

2: this("some string");

3:

4: } 5:

6: public StudentRecord(String temp){

7: this.name = temp;

8: } 9:

10: public static void main( String[] args ) 11: {

12:

13: StudentRecord annaRecord = new StudentRecord();

14: }

“this” Reference The this reference:

‰ Refers to current object instance itself

‰ Used to access the instance variables shadowed by the parameters

‰ To use the this reference, you type, this.<nameOfTheInstanceVariable>

‰ You can only use the this reference for instance variables and not for static or class variables

The this reference is assumed when you call a method from the same object.

public class MyClass { void aMethod() {

// same thing as this.anotherMethod() anotherMethod();

}

void anotherMethod() {

// method definition here...

} }

Example of “this” Reference public void setAge( int age ){

this.age = age;

}

Declaring Methods

To declare methods you write,

<modifier> <returnType>

<name>(<parameter>*) { <statement>*

} Where:

‰ <modifier> can carry a number of different modifiers

‰ <returnType> can be any data type (including void)

‰ <name> can be any valid identifier

‰ <parameter> can be one or more parameters passed as argument to the method.

Each <parameter> is associated with a parameter type (primitive or object) and a parameter name.

Accessor (Getter) Methods Accessor methods:

‰ Used to read values from your class variables (instance or static)

‰ Usually written as get<NameOfInstanceVariable>

‰ It also returns a value

Example 1: Accessor (Getter) Method Example:

public class StudentRecord { private String name;

‰ public means that the method can be called from objects outside the class.

‰ String is the return type of the method. This means that the method should return a value of type String.

‰ getName is the name of the method.

‰ () means that your method does not have any parameters.

Example 2: Accessor (Getter) Method public class StudentRecord { private String name;

// some code

// An example in which the business logic is

// used to return a value on an accessor method public double getAverage(){

double result = 0;

result=(mathGrade+englishGrade+scienceGrade)/3;

return result;

} }

Mutator (Setter) Methods Mutator Methods:

‰ Used to write or change values of your class variables (instance orstatic)

‰ Usually written as set<NameOfInstanceVariable>

Example: Mutator (Setter) Method Example:

public class StudentRecord { private String name;

‰ public means that the method can be called from objects outside the class.

‰ void means that the method does not return any value.

‰ setName is the name of the method.

‰ (String temp) is a parameter that will be used inside your method.

Multiple Return Statements

‰ You can have multiple return statements for a method as long as they are not on the same block.

‰ You can also use constants to return values instead of variables.

Example: Multiple Return Statements

public String getNumberInWords( int num ){

String defaultNum = "zero";

return defaultNum;

}

Static Methods Example:

public class StudentRecord {

private static int studentCount;

public static int getStudentCount(){

return studentCount;

} } where,

‰ public means that the method can be called from objects outside the class.

‰ static means that the method is static and should be called by typing, [ClassName].[methodName. For example, in this case, you call the method StudentRecord.getStudentCount()

‰ int is the return type of the method. This means that the method should return a value of type int.

‰ getStudentCount is the name of the method.

‰ () means that your method does not have any parameters.

Coding Guidelines

‰ Method names should start with a small letter

‰ Method names should be verbs

‰ Always provide documentation before the declaration of the method

When to Define Static Method?

When the logic and state does not involve specific object instance:

‰ Computation method: add(int x, int y) method

When the logic is a convenience without creating an object instance:

‰ Integer.parseInt();

Source Code for StudentRecord Class public class StudentRecord {

// Instance variables

private double average;

private static int studentCount;

/**

* Returns the name of the student (Accessor method) */

public String getName(){

return name;

} /**

* Changes the name of the student (Mutator method)

*/

public void setName( String temp ){

name = temp;

} /**

* Computes the average of the english, math and science * grades (Accessor method)

*/

public double getAverage(){

double result = 0;

result = ( mathGrade+englishGrade+scienceGrade )/3;

return result;

} /**

* returns the number of instances of StudentRecords * (Accessor method)

*/

public static int getStudentCount(){

return studentCount;

}

Sample Source Code that uses StudentRecord Class public class StudentRecordExample

{

public static void main( String[] args ){

//create three objects for Student record

StudentRecord annaRecord = new StudentRecord();

StudentRecord beahRecord = new StudentRecord();

StudentRecord crisRecord = new StudentRecord();

//set the name of the students annaRecord.setName("Anna");

beahRecord.setName("Beah");

crisRecord.setName("Cris");

//print anna's name

System.out.println( annaRecord.getName() );

//print number of students

System.out.println("Count="+StudentRecord.getStudentCount());

} }

Program Output Anna

Student Count = 0

Try It Out

Problem Statement:

Write a program that illustrate the use of ‘this’ statement in constructor overloading.

Code:

public class Box {

double x, y, width, height;

public Box(double x, double y, double width, double height) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;

}

public Box(double x, double y) { this(x, y, 10, 10);

}

// continued …

Refer File Name: Box.java to obtain soft copy of the program code

How It Works:

‰ The first Box() constructor takes the arguments x, y, width, and height and assigns them to the appropriate field variables.

‰ The second Box() constructor takes just the coordinates of the box as arguments and invokes the first constructor, passing 10 as the default value for the height and width of the box.

‰ The third constructor has no arguments and invokes the second constructor with the default value of 1 for the x and y coordinates of the box.

‰ The this(x,y,10,10) and this(1,1) used in the second and third constructors is a special notation provided by Java to enable you to invoke a constructor of the same class from another constructor of that class.

‰ It is referred to as a constructor call statement. In order to use a constructor call statement, there must be a constructor whose argument list matches those supplied with this() .

‰ Note: If this() appears in a constructor, then it must appear as the first statement in the constructor.

Tips and Tricks:

‰ How can you differentiate a constructor from a method?

‰ Can you also have a method that has the same name as the class?

‰ Are constructors inherited? If you do not provide a constructor but your superclass does,then do you get the superclass constructor instead of the default?

‰ A static method cannot access a variable that is not static.

‰ But can a method that is not static access a static variable?

Solution:

‰ Java lets you to declare a method with the same name as your class, which does not make it a constructor, though.

‰ The thing that separates a method from a constructor is the return type.

‰ Methods must have a return type, but constructors cannot have a return type and not even void.

‰ No, constructors are not inherited.

‰ A method that is not static in a class can always call a static method in the class or access a static variable of the class.

Summary

‰ A constructor is always invoked when a new object is created.

‰ Every class, even an abstract class, has at least one constructor.

‰ Interfaces do not have constructors.

‰ Constructors must have the same name as the class.

‰ Constructors can use any access modifier (even private!)

‰ The default constructor is a no-arg constructor with a no-arg call to super().

‰ The first statement of every constructor must be a call to either this() (an overloaded constructor) or super().

‰ Calls to this() and super() cannot be in the same constructor, you can have one or the other, but never both.

Test Your Understanding

1. The overloaded constructors in a class will have:

a) Different names

b) Different parameter names c) Different return types d) None of these

2. How many constructors can a class have?

3. What is the advantage of using the ‘this’ keyword?

Session 38: Access Specifiers, Constructors and Methods

Learning Objectives

After completing this session, you will be able to:

‰ Explain method overloading

Method Overloading Method overloading:

‰ Allows a method with the same name but different parameters, to have different implementations and return values of different types

‰ Can be applied when the same operation has different implementations

‰ Always remember that overloaded methods have the following properties:

‰ The same method name

‰ Different parameters or different number of parameters

‰ Return types can be different or same Example of Method Overloading

public void print( String temp ){

System.out.println("Name:" + name);

System.out.println("Address:" + address);

System.out.println("Age:" + age);

}

public void print(double eGrade, double mGrade, double sGrade)

System.out.println("Name:" + name);

System.out.println("Math Grade:" + mGrade);

System.out.println("English Grade:" + eGrade);

System.out.println("Science Grade:" + sGrade);

}

public static void main( String[] args ) {

StudentRecord annaRecord = new StudentRecord();

annaRecord.setName("Anna");

annaRecord.setAddress("Philippines");

annaRecord.setAge(15);

annaRecord.setMathGrade(80);

annaRecord.setEnglishGrade(95.5);

annaRecord.setScienceGrade(100);

//overloaded methods

annaRecord.print( annaRecord.getName() );

annaRecord.print( annaRecord.getEnglishGrade(), annaRecord.getMathGrade(), annaRecord.getScienceGrade());

}

Program Output

You will have the output for the first call to print:

Name:Anna

Address:Philippines Age:15

You will have the output for the second call to print:

Name:Anna

Write a program that illustrates invoking overloaded methods.

Code:

class TestAdder {

public int addThem(int x, int y) {

System.out.println("Inside addThem(int x, int y) method...");

return x + y;

}

// Overload the addThem method to add doubles instead of ints public double addThem(double x, double y) {

System.out.println("Inside addThem(double x, double y) method...");

return x + y;

} }

//From another class, invoke the addThem() method public class TestAdder {

public static void main(String[] args) { Adder a = new Adder();

int b = 27;

int c = 3;

int result = a.addThem(b, c); // which addThem is invoked?

double doubleResult = a.addThem(22.5, 9.3); // which addThem?

} }

Refer File Name: TestAdder.java to obtain soft copy of the program code

How It Works:

‰ In the TestAdder program, the first call to a.addThem(b,c) passes two ints to the method.

‰ So, for the above call, the first version of addThem() – the overloaded method that contains two int arguments – is done.

‰ The second call to a.addThem(22.5, 9.3) passes two doubles to the method.

‰ So, for the above call, the second version of addThem() – the overloaded method that contains two double arguments – is done.

Tips and Tricks:

Differentiate between Overloading methods and Overriding methods.

Solution:

Overloading Overriding

Signature has to be different. Just a difference in return type is not enough.

Signature has to be the same. (including the return type)

Accessibility may vary freely. Overriding methods cannot be more private than the overridden methods.

Just the name is reused. Methods are independent methods. Resolved at compile-time based on method signature.

Related directly to sub-classing. Overrides the parent class method. Resolved at run-time based on type of the object.

Can call each other by providing appropriate argument list.

Overriding method can call overridden method by super.methodName() , this can be used only to access the immediate method of superclass.

super.super will not work. Also, a class outside the inheritance hierarchy cannot use this technique.

Methods can be static or non-static. If two methods have the same signature, declaring one as static and another as non-static does not provide a valid overload. It’s a compile time error.

static methods do not participate in overriding, since they are resolved at compile time based on the type of reference variable. A static method in a sub-class cannot use super. A static method cannot be overridden to be non-static and vice-versa.

There is no limit on number of overloaded methods a class can have.

Each parent class method may be overridden at most once in any sub-class.

Summary

‰ Methods can be overridden or overloaded; constructors can be overloaded but not overridden.

‰ Overloading means reusing a method name, but with different arguments.

‰ Overloaded methods:

o Must have different argument lists

o May have different return types, if argument lists are also different o May have different access modifiers

o May throw different exceptions

‰ Methods from a superclass can be overloaded in a subclass.

‰ Reference type determines which overloaded method will be used at compile time.

Test Your Understanding

1. What is meant by method overloading’?

2. Differentiate between constructor overloading and method overloading.

Session 39: Access Specifiers, Constructors and Methods

Learning Objectives

After completing this session, you will be able to:

‰ Apply access modifiers

Access Modifiers

You can define the scope of a variable or method or class by using the access modifiers.

There are four different types of access modifiers in Java:

‰ public (Least restrictive)

‰ protected

‰ default

‰ private (Most restrictive)

The first three access modifiers are explicitly written in the code to indicate the access type, for the third one, which is default, no keyword is used.

public Accessibility Public access:

‰ Specifies that class members (variables or methods) are accessible to anyone, both inside and outside the class and outside of the package

‰ Any object that interacts with the class can have access to the public members of the class

Keyword: public

Example: “public” Access Modifier public class StudentRecord {

//default access to instance variable public int name;

//default access to method public String getName(){

return name;

} }

protected Accessibility Protected access:

‰ Specifies that the class members are accessible only to methods in that class and the subclasses of the class

‰ The subclass can be in different packages Keyword: protected

Example: “protected” Access Modifier public class StudentRecord {

//default access to instance variable protected int name;

//default access to method protected String getName(){

return name;

} }

default Accessibility Default access:

‰ Specifies that only classes in the same package can have access to the variables and methods of the class

‰ No actual keyword is their for the default modifier and it is applied in the absence of an access modifier

Example: “default” Access Modifier public class StudentRecord {

//default access to instance variable int name;

//default access to method String getName(){

return name;

} }

private Accessibility

Private accessibility: Specifies that the class members are only accessible by the class in which they are defined

Keyword: private

Example: “private” Access Modifier public class StudentRecord {

//default access to instance variable private int name;

//default access to method private String getName(){

return name;

} }

Java Program Structure: The Access Modifiers

Coding Guidelines

The instance variables of a class should normally be declared private, and the class will just provide accessor (getter) and mutator (setter) methods to these variables.

Try It Out

Problem Statement:

Write a program that illustrates about access modifiers.

Code:

package learn;

public class OtherClass {

void testIt() { // No modifier means method has default access System.out.println(“OtherClass”);

} }

--- In another source code, you have the following:

package somethingElse;

import learn.OtherClass;

class AccessClass {

Refer Files : OtherClass.java, AccessClass.java to obtain soft copy of the program code

How It Works:

‰ In the OtherClass program, the testIt() method has default (think: package-level) access.

‰ Notice also that class OtherClass is in a different package from the AccessClass.

‰ Now the question is, will AccessClass be able to apply the method testIt() ? Will it cause a compiler error?

‰ No method matching testIt()is found in class learn.OtherClass. o.testIt();.

‰ From the preceding results, you can see that AccessClass cannot use the OtherClass method testIt() because testIt() has default access, and AccessClass is not in the same package as OtherClass. So AccessClass cannot see it, and hence the compiler complains.

Tips and Tricks:

Provide the key tips on access modifiers in Java.

Solution:

‰ Access modifiers can be public, protected, and private.

‰ If no access modifier is specified, then the accessibility is default package visibility. All classes in the same package can access the feature. It is called as friendly access.

But friendly is not a Java keyword. Same directory is same package in consideration of Java.

‰ ‘private’ means only the class can access it and not even sub-classes. So, it will cause access denial to the variable or method of the sub class.

‰ These modifiers dictate, which classes can access the features. An instance of a class can access the private features of another instance of the same class.

‰ ‘protected’ means all classes in the same package (like default) and sub-classes in any package can access the features. But a subclass in another package can access the protected members in the super-class by only the references of subclass or its subclasses. A subclass in the same package does not have this restriction. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.

‰ Methods cannot be overridden to be more private. Only the direction shown in following figure is permitted from parent classes to sub-classes.

private --> friendly (default) --> protected --> public

Parent classes Sub-classes

Summary

The different access modifiers in Java are default, public, private, and protected.

Test Your Understanding

1. State true or false for the following:

a) For the default (or package-level access), the keyword default is used.

b) protected variables and methods can be accessed by all members of subclasses in different packages.

In document Core Java Handout v1.0 (Page 145-164)