0% found this document useful (0 votes)
46 views

Lecture05 Annotated

The document discusses Java packages, which are used to avoid name conflicts by grouping similar classes and interfaces, and how packages are represented in the file system; it also covers encapsulation through access modifiers like public, private, and default, and how getter and setter methods are used to control access to private variables.

Uploaded by

Lewi Fasil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Lecture05 Annotated

The document discusses Java packages, which are used to avoid name conflicts by grouping similar classes and interfaces, and how packages are represented in the file system; it also covers encapsulation through access modifiers like public, private, and default, and how getter and setter methods are used to control access to private variables.

Uploaded by

Lewi Fasil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

COE 318

Introduction to Software Design


Lecture 05

Dr. Naimul Khan


Office: Virtual
Office Hour: By Appointment
Java Packages
• Package are used in Java, in-order to avoid
name conflicts. A package can be defined as
a group of similar types of classes and
interface. Using package it becomes easier
to locate the related classes
Java Packages
• Built-in Package: Existing Java package for
example java.lang, java.util etc.
• User-defined-package: Java package created
by user to categorized classes
Java Packages
• Java uses file system directory to store
package. For example the .class for any
classes you to define to be part of a package
package must be stored in a directory called
mypack
package coe318;
public class Lab3 { Declaring a package
int labNum=3; with the "package" keyword
(NetBeans does it automatically)
}

//this code is in another package Using the class OUTSIDE the


import coe318.*;
same package requires use of the
public static void main (String[] args) {
Lab3 l=new Lab3();
"import" keyword
} Option 1: import everything
Can make code slow if
package is big
//this code is in another package
import coe318.Lab3;
public static void main (String[] args) {
Option 2: import specific class
Lab3 l=new Lab3();
}
Encapsulation
• A program or object may use methods from
another object.
• To protect the instance variables, we should
make it difficult for a main() or object to
access another object’s variables directly.
• Hiding the variables within the class, and
making it available only through the
methods is known as encapsulation.
Visibility Modifiers
• We accomplish encapsulation through the
appropriate use of visibility modifiers
• Java has three visibility modifiers: public,
private and protected.
• The protected modifier involves inheritance,
which we will discuss later.
• If no modifier mentioned – default access
modifier: variables accessible by any class
in the same package.
public vs private
• Instance variables of a class that are
declared with public visibility can be
referenced anywhere.
• Methods and variables that are declared
private can only be accessed within the
declared class itself.
Default (no modifier)
public class Car {
String licensePlate;
double speed;
double maxSpeed;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
public class CarTest {
} public static void main(String[] args){
Car miniVan = new Car("ABC", 50, 100);
miniVan.licensePlate="GHI";
miniVan.speed="100";
}
}
Default (no modifier)
public class Car {
String licensePlate;
double speed;
double maxSpeed;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber; Different class
speed=speedVal; (if main() was in same class,
maxSpeed=maxVal; Access modifier wouldn't matter)
}
public class CarTest {
} public static void main(String[] args){
Car miniVan = new Car("ABC", 50, 100);
miniVan.licensePlate="GHI"; OK
miniVan.speed="100"; OK
}
}
Public and private
public class Car {
private String licensePlate;
public double speed;
public double maxSpeed;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
public class CarTest {
} public static void main(String[] args){
Car miniVan = new Car("ABC", 50, 100);
miniVan.licensePlate="GHI"; Illegal!
miniVan.speed=100; OK
}
}
class Modifiers {
public int pubData;
private int privData;

private void privMethod( ) {}

public void pubMethod( ) {


privMethod( ); //private method is called from within the same class, OK
}
}
class ModifierDemo {
public static void main( String[ ] args ) {
Modifiers mod = new Modifiers( );
mod.pubData = 1; // Okay: pubData is public
mod.pubMethod( ); // Okay: pubMethod is public
mod.privData = 1; // Illegal! privData is private
mod.privMethod( ); // Illegal! privMethod is private
}
}
Rule of Thumb for
Visibility Modifiers
• As a general rule, no object's Instance
Variables should be declared with public
visibility.
• Public variables violate encapsulation
because they allow the client to “reach in”
and modify the values directly
Rule of Thumb for
Visibility Modifiers
• Methods that provide the object's services
are declared with public visibility so that
they can be invoked by clients
• Public methods are also called service
methods
• Typically methods are public.
• A private method created simply to assist a
service method is called a support method
Accessor (getter) and
Mutator (setter)
• Because instance variable is private, a class
usually provides methods to access and
modify instance variable values.
• An accessor (getter) method returns the
current value of a variable.
• A mutator (setter) method changes the value
of a variable.
Encapsulation enforced
• A combination of access modifiers,
constructors, and getter/setter methods can
help only exposing the instance variables
that a developer wants to be exposed.
• The rest can be set through Constructors.
Encapsulated Car class from Lecture
2 (only speed has getter/setter)
public class Car {
private String licensePlate;
private double speed;
private double maxSpeed;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}

}
Scope of a variable: Instance
variables have class scope
• The instance variables of a class have class
scope. Class scope begins at the opening
left brace and ends at the closing right brace
of the class definition.
• Class scope allows any method in the class
to directly access any instance variable.
• In effect, instance variables are "global
variables" within a class
Scope of a variable: Local
variables have block scope
• A block is a compound statement and
consists of all the statements between an
opening and closing brace.
• Local variables defined within a block have
block scope; not visible outside the block.
• A local variable can have the same name as
an instance variable. In this case the
instance variable is hidden from the method
by the local (hence the "this" keyword).
public class Point {
private double x,y; // instance variables
public Point() {
x = 1; // same variables as instance variables
y = 1;}
public Point (double x, double y){
this.x = x; // this.x refers to instance variable
this.y = y;
this.x++;
System.out.println("this.x = " + this.x);
System.out.println("x = " + x); // parameter variable
}
public Point (double x, double y, boolean dummy) {
x++;
System.out.println("x = " + x);
}
} Point p1= new Point();
Point p2= new Point(2,3);
Point p3=new Point(2,3,false);
public class A {
Find output
private A next;
private int v;
public A(A n, int i) {
v = i;
next = n;
}
public int getT() {
int t = v;
if (next != null) {
t = t + next.getT();
}
return t;
}
public static void main(String[] args) {
A a = new A(null, 3);
A b = new A(a, 1);
A c = new A(b, 2);
System.out.println(a.getT());
System.out.println(b.getT());
System.out.println(c.getT()); }}
public class A {
Given the following
private A next; program output,
private int v; Fill in the blanks
public A(A n, int i) {
v = i;
next = n;
}
public int getT() {
int t = v;
if (next != null) {
t = t + next.getT();
}
return t;
}
public static void main(String[] args) {
A a = new A(____, ____);
A ___ = new A(____, 1);
A ___ = new A(____, 2);
System.out.println(a.getT()); 5
System.out.println(b.getT()); 8
System.out.println(c.getT()); }} 6
Arrays as parameters
• Passing entire array = pass by reference =
same behavior as passing any object

void aProc() {
int[] xyz = new int[12];
theProc(xyz);
System.out.println(xyz[3]);
}
void theProc(int[] mno)
{
mno[3] = 15;
}
Arrays as parameters
• Passing individual array element= pass by
value= same behavior as passing a primitive

void aProc() {
int[] xyz = new int[12];
theProc(xyz[3]);
System.out.println(xyz[3]);
}
void theProc(int mno)
{
mno = 15;
}
public class ArrayTest { Given the following
public static void main(String[] args) {
int[] test = new int[2];
program output,
test[0] = 10; Fill in the blanks
test[1] = 5;
System.out.println(test[0] + "," + test[1]); 10, 5
fiddle(test, test[1]);
System.out.println(test[0] + "," + test[1]); 19, 15
}
static void fiddle(int[] test, int element) {
___ = 15;
___ = 19;
____ = 12;
System.out.println(___+ "," + ___ + ","
+ element); 15, 19,12
test = new int[2];
test[0] = ___;
test[1] = ___;
System.out.println(test[0] + "," + test[1]); 20, 21
}}
Two Dimensional (2D) Arrays
2D Arrays - initializing
int[][] A = { { 1, 0, 12, -1 },
{ 7, -3, 2, 5 },
{ -5, -2, 2, 9 }
};

or
int[][] A = new int[3][4];
A.length: the number of rows of A.
A[0].length: the number of columns in A
A[1].length : the number of columns in A
A[2].length : …..
Two Dimensional (2D) Arrays
public class TwoDArray
{
public static void main (String[] args)
{
int[][] table = new int[5][10];
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = row * 10 + col;

for (int row=0; row < table.length; row++)


{
for (int col=0; col < table[row].length; col++)
System.out.println (table[row][col]);
}
}
}
2D arrays of objects
public class 2DArray
{
public static void main (String[] args)
{
String [][] A = {
{"Hello", "World" },
{"Guten", "Welt"}
};

for (int row=0; row < A.length; row++){


for (int col=0; col < A[row].length; col++)
System.out.println (A[row][col]);
}
}
}
Interaction -
taking input from user
• Java has a nice built-in class Scanner that
can simplify taking input from the user.
• The Scanner class is part of the java.util
class library (package), and must be
imported into a program to be used.
Instantiating Scanner

import java.util.Scanner; import java.util.Scanner;


…. ….
…… ……
Scanner s= new Scanner(System.in); Scanner s= new Scanner(new FileReader("myfile")

If you want to read If you want to read


from console from file
Reading a line with Scanner
import java.util.Scanner;
class Echo {
public static void main (String[] args) {
String message;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a line of text:");
message = scan.nextLine(); //app waits here for user input
System.out.println ("You entered:" + message);
}}
Looping input
with stop condition
import java.util.Scanner;
class Echo {
public static void main (String[] args) {
String message="";
Scanner scan = new Scanner (System.in);
while(!message.Equals("quit")){
System.out.println ("Enter a line of text:");
message = scan.nextLine();
System.out.println ("You entered:" + message);
}
} //can you make this code case-insensitive? (hint:
} toLowerCase())
Reading input as Tokens
• A Scanner breaks its input into elements
(tokens) using a white space. The resulting
tokens may then be converted into values of
different types using various methods
already defined in the Scanner class.
Reading input as Tokens
import java.util.Scanner;
class Age {
public static void main (String[] args) {
String message;
Scanner scan = new Scanner (System.in);
System.out.println("Enter your first name & year of birth");
String firstName=scan.next(); //reads string till finds a space
int yob=scan.nextInt(); //reads int till finds a space
System.out.println("Hello "+firstName + "," + "you are " +
(2021-yob)+ " years old!");
}
}
Reading input as Tokens
• Scanner methods that read numeric data
throw exception (error) if the next value
isn't what the method expects.
• Boolean methods can help checking ahead.
Fixing the Age class with checks
import java.util.Scanner;
class Age {
public static void main (String[] args) {
String message;
Scanner scan = new Scanner (System.in);
System.out.println("Enter your first name & year of birth");
String firstName=scan.next(); //reads string till finds a space
if(scan.hasNextInt()){
int yob=scan.nextInt(); //reads int till finds a space
System.out.println("Hello "+firstName + "," + "you are " +
(2021-yob)+ " years old!");}
else
System.out.println("Input error!");
}
}
• Write a class Triangle
– Three sides, accessors and one mutator methods.
– A method that calculates the perimeter of a triangle
• Write a tester class, TriangleDemo.java.
– prompt the user for the triangle sides
– report the sides of the triangle
– report the triangle's perimeter
Triangle class
class Triangle {
//Instance variable
private double side1;
private double side2;
private double side3;

}
Accessors (getters)
class Triangle {
//Instance variable
private double side1;
private double side2;
private double side3;
public double GetSide1() {
return side1;
}
public double GetSide2() {
return side2;
}
public double GetSide3() {
return side3;}
}
Mutator (setter)
class Triangle {
//Instance variable
private double side1;
private double side2;
private double side3;
public double GetSide1() {
return side1;
}
public double GetSide2() {
return side2;
}
public double GetSide3() {
return side3;}
public void setSides (double side1, double side2, double side3){
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;}
}
getPerimeter()
class Triangle {
//Instance variable
private double side1;
private double side2;
private double side3;
public double GetSide1() {
return side1;
}
public double GetSide2() {
return side2;
}
public double GetSide3() {
return side3;}
public void setSides (double side1, double side2, double side3){
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;}
public double getPerimeter(){
return side1+side2+side3;
}
}
TriangleTest
import java.util.Scanner
class TriangleTest{
public static void main (String[] args) {
double side1, side2, side3;
Scanner scan = new Scanner (System.in);
System.out.println(“Your Side1, Side2 and Side3:”);
side1= scan.nextDouble();
side2 = scan.nextDouble();
side3 = scan.nextDouble();
Triangle tri = new Triangle();
tri.setSides(side1, side2, side3);
System.out.println(tri.getPerimeter());
}
}

You might also like