07 Sp20 Java Programming Essentials
07 Sp20 Java Programming Essentials
Lecture 07
Course Instructor: Dr Usman Nasir
Course Code: SE331
Spring 2020
Y2020Ver 1.0
Java Class, Association & Inheritance
public class Bicycle {// in file: Bicycle.java
public String currentState() { return " speed:" + speed + " gear:" + gear; }
}//end of class
public class BicycleDemo {
public static void main(String[] args) {
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
bike2.speedUp(10);
Output:
bike2.changeGear(2); speed:10 gear:2
bike2.applyBrakes(5); speed:5 gear:3
bike2.changeGear(3);
System.out.println(bike2.currentState());
}
}
Association
BicycleDemo uses objects of Bicycle
This makes BicycleDemo has-a relationship with Bicycle
mtbike2.speedUp(100);
mtbike2.applyBrakes(5);
System.out.println(mtbike2.currentState()); Output:
}
} speed:20 gear:2
speed:95 gear:1
Java Interface
Java Interface
An interface is a reference type, similar to a class but
it can contain only constants and method signatures
// Rectangle
public class Rectangle implements Shape {
public void giveArea( )
{//implementation of giveArea( )
}
}//
Will this code compile?
public interface Shape {
public void hello();
public void giveArea();
}
// Rectangle
NO, why
public class Rectangle implements Shape {
public void giveArea(){}
}
Will this code compile?
public interface Shape {
private int area = 0;
public void giveArea();
}
// Rectangle
NO, why
public class Rectangle implements Shape {
public void giveArea( ){ };
}
An instance of class that implements an interface can
stored in a reference of that interface.
Example:
public interface Greeter {
public void sayHello( );
}
public class Face implements Greeter {
public void sayHello( ) { System.out.println(“Hello”); }
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
public class Game implements Football {
public void setHomeTeam(String name){ };
public void setVisitingTeam(String name){};
Example:
//public interface Event{ }
//public interface Sports{ }
// Filename: Football.java
public interface Football {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
}
public class Game implements Sports, Football {
public void setHomeTeam(String name){ };
}//end of class
public class Hand implements IHumanBodyPart{
@Override
public void oldExistingMethod(){
System.out.println("oldExistingMethod in
Hand");
}
@Override
public void newDefaultMethod() {
System.out.println("newDefaultMethod
overridden in Hand");
}}//end of class
public static void main(String[] args) {
IHumanBodyPart reference= new Face();
reference.oldExistingMethod();
reference.newDefaultMethod();
IHumanBodyPart referenceTwo= new Hand();
referenceTwo.oldExistingMethod();
referenceTwo.newDefaultMethod();
System.out.println("__________________");
nullList.add( null );
System.out.println( "Case B:" + nullList.isEmpty() ); Case B: false
nullList.remove( 0 );
System.out.println( "Case C:" + nullList.isEmpty() ); Case C: true
nullList.add( "" );
System.out.println( "Case D:" + nullList.isEmpty() ); Case D: false
nullList.clear( );
System.out.println( "Case E:" + nullList.isEmpty() ); }} Case E: true
Searching for an Element
Linear search within an ArrayList starts from the
first element.
A method int indexOf(Object element) does linear search
int indexOf(Object element) returns the index of the first
occurrence of element
returns -1 if element is not found.
Methods in Iterator
boolean hasNext() // Returns true if not all elements have
been visited
E next() // Returns the next element of the list,
void remove() // Remove from the list the element just
returned by next()
import java.util.* ;
public class IteratorExample{
public static void main ( String[ ] args) {
ArrayList<String> names = new ArrayList<String>();
names.add( “Javaid Ch" ); names.add( "Dr Moeed" );
names.add( "Waseem Badami" ); names.add( "Kashif Abbasi" );
names.add( "Sana Bucha" );
Element: Javaid Ch
// Create an iterator for the list Element: Dr Moeed
Iterator<String> iter = names.iterator(); Element: Waseem Badami
// Use the iterator to visit each element Element: Kashif Abbasi
while ( iter.hasNext() ) Element: Sana Bucha
System.out.println("Element: "+ iter.next() );
}
}
The enhanced for loop (a.k.a "for each" loop) can be
used with any class that implements the Iterable
interface, such as ArrayList.
public class IteratorExampleTwo{
public static void main ( String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add( "Gen. Aziz" ); names.add( ”Gen. Moeed" );
names.add( ”Lt. Badami" ); names.add( ”Col. Kashif Abbasi" );
int i=0;
for ( String nm : names ){
System.out.println("Element: "+i+" "+ nm );
i++;
}
Element: 0 Gen. Aziz
}
Element: 1 Gen. Moeed
} Element: 2 Lt Badami
Element: 3 Col Kashif Abbasi
Using Wrapper classes with ArrayList
To put an int into an ArrayList we put the int inside of an
Integer object (Integer is a wrapper class).
Output
989898989
667676766
false// ???
Output
true
false
true// Should this happen??
@Override
public int hashCode() {
return getId();
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Student))
return false;
if (obj == this) return true;
return this.getId() == ((Student) obj).getId();
}
}
Of hashcodes are not equals just return false
if (obj.hashCode() != this.hashCode())
return false;
class Entry {
private String name, number;
public Entry( String n, String num ) { name = n; number = num; }
public String getName() { return name ; }
public String getNumber() { return number ; }
Quick fix
Java Programming Style Guide
Programming style guides are guidelines that cover
aesthetic issues of formatting, code writing
conventions or coding standards.
Java coding follows these hard-and-fast rules universally
Some famous style guides are
Java Sun Style guide
Google Java Style Guide
https://google.github.io/styleguide/javaguide.html
Some style that you should adhere to during Java
coding
Case Conventions
Variables, fields and methods:
start with lowercase, use caps for new words (camelCase):
name
sayHello
Classes:
start with uppercase, use caps for new words (PascalCase
aka UpperCamelCase):
Greeter
ArrayList
Constants:
use all caps, underscores to separate words
PI
MAX_VALUES
Property Access
Common to use get/set prefixes:
public String getName()
void setName(String newValue)
Boolean property has is/set prefixes:
public boolean isPolite()
public void setPolite(boolean newValue)
Braces
"Allman" brace style: braces line up.
public String sayHello()
{
return "Hello, " + name + "!";
}
No magic numbers
Bad Good
h = 31 * h + val[off]; final int HASH_MULTIPLIER = 31;
h = HASH_MULTIPLIER * h + val[off];
Always use
@Override with overridden methods
Will explain this later
Thank you!!
Read up and do exercise on ArrayList, HashSet and
HashMap, HashTable
Exam Questions from this lecture
Problem statement to Interface, Abstract classes
Code output or finding errors etc….
Converting wrong code and fix it.
Using ArrayList, HashSet etc……
Finding errors in Java and correcting it