SlideShare ist ein Scribd-Unternehmen logo
1 von 12
2016 Winter
LAB #5
Prepared by: Berk Soysal
2016 Winter
Java Generic methods and generic classes enable
programmers to specify, with a single method declaration,
a set of related methods or, with a single class declaration,
a set of related types, respectively.
public class GenericMethodTest {
public static < E > void printArray( E[] inputArray ) {
for ( E element : inputArray ){
System.out.print( "%s ", element ); }
}
public static void main( String args[] ) {
Integer[] intArray = { 1, 2, 3, 4, 5 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
printArray( intArray ); // pass an Integer array
printArray(charArray); // pass a Character array
} }
E becomes
Integer
and then
Character
2016 Winter
Let’s revisit the class Combination from laboratory 2 with only 2 inputs.
Make all the necessary changes to the class Combination so that it
implements the interface java.lang.Comparable.
if(first<other.first) result = -1;
else if(first>other.first) result = 1;
…
else result=0;
The interface Comparable is part of a package, called lang, that is
imported by default. Therefore, no need to import Comparable.
Write a test program for thoroughly testing your implementation.
2016 Winter
An interface is a way to describe what classes should
do, without specifying how they should do it. It’s not a class
but a set of requirements for classes that want to conform
to the interface, for example;
public interface Comparable<E> {
public int compareTo(E other);
}
This requires that any class implementing the Comparable
interface contains a compareTo method, and this method must
take an Object parameter and return an integer.
2016 Winter
• Once a Java class implements an Java interface you can use an instance of that
class as an instance of that interface. Here is an example:
MInterface myInterface = new MInterfaceImpl();
myInterface.sayHello();
• Notice how the variable is declared to be of the interface type MInterface
while the object created is of type MInterfaceImpl.
• Java allows this because the class MInterfaceImpl implements the MInterface
interface. You can then reference instances of the MInterfaceImpl class as
instances of the MInterface interface.
• You cannot create instances of a Java interface by itself. You must always create
an instance of some class that implements the interface, and reference that
instance as an instance of the interface.
2016 Winter
A stack is a data structure that allows data to be inserted (a 'push'
operation), and removed (a 'pop' operation).
Are Stacks LIFO or FIFO ?
- They are Last In First Out
2016 Winter
• Let’s edit the Stack.java and add an abstract void method clear() to the
class.
• Create a class called ArrayStack that uses a fixed-size array and
implements the interface Stack.
• Now that the interface Stack has been modified to have a method
clear(), the current implementation of the class ArrayStack is broken
(try compiling it without making any change, what is the error message
displayed?).
• Since the class ArrayStack implements the interface Stack, it has to
provide an implementation for all the methods that are declared by the
interface. Consequently, write an implementation for the method
void clear(). It removes all of the elements from this ArrayStack.
• The stack will be empty after this call returns.
2016 Winter
• The class Balanced contains a simple algorithm to validate expressions.
• Observation: for an expression consisting of well balanced parentheses
the number of opening ones is the same as the closing ones.
> run Balanced {[()]}
algo1( "{[()]}" ) -> true
2016 Winter
• Perform the same operation using the ArrayStack.java and Stack.java
> run Balanced {[()]}
algo1( "{[()]}" ) -> true
algo2( "{[()]}" ) -> true
2016 Winter
• A Canadian postal code example: K1N 8A7 A US zip code example: FL 33130
Write a test class for the above classes.
• Declare an array, called codes, to hold exactly 100 postal codes.
• Create n = 10 postal codes, some are USZipCodes, some are CanadianPostalCodes,
some must
be valid and some must not be valid. Store these codes in the n left most positions of
the array;
• Knowing that exactly n postal codes are currently stored in the left most cells of the
array, write
a for loop to count the number of valid codes.
PostalCode
CanadianPostalCode USZipCode
Abstract class PostalCode
Constructor accepts String code.
Abstract boolean isValid();
String getCode()
2016 Winter
Java Tutorial Lab 5

Weitere ähnliche Inhalte

Was ist angesagt?

Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 

Was ist angesagt? (20)

Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overriding
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 

Ähnlich wie Java Tutorial Lab 5

Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
vannagoforth
 

Ähnlich wie Java Tutorial Lab 5 (20)

Java Tutorial Lab 4
Java Tutorial Lab 4Java Tutorial Lab 4
Java Tutorial Lab 4
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
 
Java best practices
Java best practicesJava best practices
Java best practices
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
 
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 4) A Concise and Practical Introduction to Programming Algorithms in...
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Annotations
AnnotationsAnnotations
Annotations
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
Interfaces .ppt
Interfaces .pptInterfaces .ppt
Interfaces .ppt
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.ppt
 

Mehr von Berk Soysal

Mehr von Berk Soysal (7)

Guest author manual
Guest author manualGuest author manual
Guest author manual
 
Comparison of BER performances of 64-PSK and 64-QAM in AWGN channels
Comparison of BER performances of  64-PSK and 64-QAM in  AWGN channelsComparison of BER performances of  64-PSK and 64-QAM in  AWGN channels
Comparison of BER performances of 64-PSK and 64-QAM in AWGN channels
 
Biomedical project report detecting emg noise
Biomedical project report detecting emg noiseBiomedical project report detecting emg noise
Biomedical project report detecting emg noise
 
Self Evaluation Test
Self Evaluation Test Self Evaluation Test
Self Evaluation Test
 
Java Tutorial Lab 9
Java Tutorial Lab 9Java Tutorial Lab 9
Java Tutorial Lab 9
 
Java Tutorial Lab 7
Java Tutorial Lab 7Java Tutorial Lab 7
Java Tutorial Lab 7
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 

Kürzlich hochgeladen

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

Java Tutorial Lab 5

  • 1. 2016 Winter LAB #5 Prepared by: Berk Soysal
  • 3. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types, respectively. public class GenericMethodTest { public static < E > void printArray( E[] inputArray ) { for ( E element : inputArray ){ System.out.print( "%s ", element ); } } public static void main( String args[] ) { Integer[] intArray = { 1, 2, 3, 4, 5 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; printArray( intArray ); // pass an Integer array printArray(charArray); // pass a Character array } } E becomes Integer and then Character 2016 Winter
  • 4. Let’s revisit the class Combination from laboratory 2 with only 2 inputs. Make all the necessary changes to the class Combination so that it implements the interface java.lang.Comparable. if(first<other.first) result = -1; else if(first>other.first) result = 1; … else result=0; The interface Comparable is part of a package, called lang, that is imported by default. Therefore, no need to import Comparable. Write a test program for thoroughly testing your implementation. 2016 Winter
  • 5. An interface is a way to describe what classes should do, without specifying how they should do it. It’s not a class but a set of requirements for classes that want to conform to the interface, for example; public interface Comparable<E> { public int compareTo(E other); } This requires that any class implementing the Comparable interface contains a compareTo method, and this method must take an Object parameter and return an integer. 2016 Winter
  • 6. • Once a Java class implements an Java interface you can use an instance of that class as an instance of that interface. Here is an example: MInterface myInterface = new MInterfaceImpl(); myInterface.sayHello(); • Notice how the variable is declared to be of the interface type MInterface while the object created is of type MInterfaceImpl. • Java allows this because the class MInterfaceImpl implements the MInterface interface. You can then reference instances of the MInterfaceImpl class as instances of the MInterface interface. • You cannot create instances of a Java interface by itself. You must always create an instance of some class that implements the interface, and reference that instance as an instance of the interface. 2016 Winter
  • 7. A stack is a data structure that allows data to be inserted (a 'push' operation), and removed (a 'pop' operation). Are Stacks LIFO or FIFO ? - They are Last In First Out 2016 Winter
  • 8. • Let’s edit the Stack.java and add an abstract void method clear() to the class. • Create a class called ArrayStack that uses a fixed-size array and implements the interface Stack. • Now that the interface Stack has been modified to have a method clear(), the current implementation of the class ArrayStack is broken (try compiling it without making any change, what is the error message displayed?). • Since the class ArrayStack implements the interface Stack, it has to provide an implementation for all the methods that are declared by the interface. Consequently, write an implementation for the method void clear(). It removes all of the elements from this ArrayStack. • The stack will be empty after this call returns. 2016 Winter
  • 9. • The class Balanced contains a simple algorithm to validate expressions. • Observation: for an expression consisting of well balanced parentheses the number of opening ones is the same as the closing ones. > run Balanced {[()]} algo1( "{[()]}" ) -> true 2016 Winter
  • 10. • Perform the same operation using the ArrayStack.java and Stack.java > run Balanced {[()]} algo1( "{[()]}" ) -> true algo2( "{[()]}" ) -> true 2016 Winter
  • 11. • A Canadian postal code example: K1N 8A7 A US zip code example: FL 33130 Write a test class for the above classes. • Declare an array, called codes, to hold exactly 100 postal codes. • Create n = 10 postal codes, some are USZipCodes, some are CanadianPostalCodes, some must be valid and some must not be valid. Store these codes in the n left most positions of the array; • Knowing that exactly n postal codes are currently stored in the left most cells of the array, write a for loop to count the number of valid codes. PostalCode CanadianPostalCode USZipCode Abstract class PostalCode Constructor accepts String code. Abstract boolean isValid(); String getCode() 2016 Winter