SlideShare a Scribd company logo
Java interface and inheritance
FOR MORE CLASSES VISIT
www.tutorialoutlet.com
public interface List<T> {
public void add(T item) throws IndexOutOfBoundsException;
public T get(int i) throws IndexOutOfBoundsException; public T
remove(int i);
public int size();
default void println() {
System.out.print("[");
for (int i = 0; i < size()-1; i++) {
System.out.print(get(i) + ",");
}
if (size() > 0) {
System.out.println(get(size()-1) + "]");
}
}
} .............................................................................................................
public class LinkedList<T> implements List<T> {
private class Node<T> {
public T value;
public Node<T> next;
}
private Node<T> head;
public void add(T item) throws IndexOutOfBoundsException {
Node<T> curr = head;
if (curr == null) {
head = new Node<>();
head.value = item;
head.next = null;
} else {
while (curr.next != null) {
curr = curr.next;
}
curr.next = new Node<>();
curr.next.value = item;
curr.next.next = null;
} } public T get(int i) throws IndexOutOfBoundsException {
if (i < 0 && i >= size()) throw new
IndexOutOfBoundsException("Element
doesn't exist at location " + i); } Node<T> curr = head;
while (i > 0) {
curr = curr.next;
i--;
}
return curr.value; public T remove(int i) { if (i < 0 && i
>= size()) throw new
IndexOutOfBoundsException("Element
doesn't exist at location " + i);
// Implement
} } public int size() {
int size = 0;
Node<T> curr = head;
while (curr != null) {
curr = curr.next;
size++;
}
return size;
} ...........................................................................................
public class Main {
public static void testList(List<String> list) {
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.println(); // Should print [a,b,c,d]
System.out.println(list.size()); // Should print 4
String second = list.get(2);
System.out.println(second); // Should print c
list.add("e");
list.add("f");
list.add("g");
list.add("h");
list.add("i");
list.add("j");
list.println(); // Should print [a,b,c,d,e,f,g,h,i,j]
try {
list.add("k"); // Should throw an error for DumbList but
work for
LinkedList
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage()); // Should print You cannot add
any more item. Only 10 allowed. for DumbLink
}
list.remove(0);
} list.println(); // Should print [b,c,d,e,f,g,h,i,j] public static void
main(String args) {
List<String> list = new DumbList<>();
//List<String> list = new LinkedList<>();
}
testList(list); } ........................................................................................
..........
class FastLinkedList<T> extends LinkedList<T> {
private int size = 0;
@Override
public void add(T item) throws IndexOutOfBoundsException {
//Implement
}
@Override
public T remove(int i) {
//Implement
}
@Override
public int size() {
return size;
}
public void prettyPrint() {
//Implement
}
} .......................................................................
public class DumbList<T> implements List<T> {
private final int MAX_SIZE = 10;
private Object array = new Object[MAX_SIZE];
private int size = 0;
public void add(T item) throws IndexOutOfBoundsException {
if (size + 1 > MAX_SIZE) {
throw new IndexOutOfBoundsException("You cannot add any
more item.
Only " + MAX_SIZE + " allowed.");
} else {
// Add implementation goes here
}
}
@SuppressWarnings("unchecked")
public T get(int i) throws IndexOutOfBoundsException {
return (T) array[i];
} public T remove(int i) {
if (i < 0 && i >= size) {
throw new IndexOutOfBoundsException("Invalid index, plesae
supply
a number between 0 and " + this.size);
} else {
@SuppressWarnings("unchecked")
T toBeRemoved = (T) array[i];
// Removal Implementation goes here
return toBeRemoved;
} } public int size() {
return size;
}
}

More Related Content

What's hot

The Ring programming language version 1.6 book - Part 49 of 189
The Ring programming language version 1.6 book - Part 49 of 189The Ring programming language version 1.6 book - Part 49 of 189
The Ring programming language version 1.6 book - Part 49 of 189
Mahmoud Samir Fayed
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
akaptur
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
Eleanor McHugh
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
 
The Ring programming language version 1.5.2 book - Part 46 of 181
The Ring programming language version 1.5.2 book - Part 46 of 181The Ring programming language version 1.5.2 book - Part 46 of 181
The Ring programming language version 1.5.2 book - Part 46 of 181
Mahmoud Samir Fayed
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
akaptur
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
Adam Dudczak
 
Collection Core Concept
Collection Core ConceptCollection Core Concept
Collection Core Concept
Rays Technologies
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
Svet Ivantchev
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
Myeongin Woo
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
Carlos V.
 
Going Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoGoing Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with Go
Eleanor McHugh
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit partsMaxim Zaks
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
Joachim Bengtsson
 
Data structures
Data structuresData structures
Data structures
gayatrigayu1
 
オレオレSecurityバンドル作っちゃいました
オレオレSecurityバンドル作っちゃいましたオレオレSecurityバンドル作っちゃいました
オレオレSecurityバンドル作っちゃいましたKatsuhiro Ogawa
 

What's hot (20)

The Ring programming language version 1.6 book - Part 49 of 189
The Ring programming language version 1.6 book - Part 49 of 189The Ring programming language version 1.6 book - Part 49 of 189
The Ring programming language version 1.6 book - Part 49 of 189
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
The Ring programming language version 1.5.2 book - Part 46 of 181
The Ring programming language version 1.5.2 book - Part 46 of 181The Ring programming language version 1.5.2 book - Part 46 of 181
The Ring programming language version 1.5.2 book - Part 46 of 181
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Collection Core Concept
Collection Core ConceptCollection Core Concept
Collection Core Concept
 
Queue oop
Queue   oopQueue   oop
Queue oop
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
Going Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with GoGoing Loopy: Adventures in Iteration with Go
Going Loopy: Adventures in Iteration with Go
 
Stack queue
Stack queueStack queue
Stack queue
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Uts
UtsUts
Uts
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Data structures
Data structuresData structures
Data structures
 
オレオレSecurityバンドル作っちゃいました
オレオレSecurityバンドル作っちゃいましたオレオレSecurityバンドル作っちゃいました
オレオレSecurityバンドル作っちゃいました
 

Similar to Java interface and inheritance

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
public class TrequeT extends AbstractListT { .pdf
  public class TrequeT extends AbstractListT {  .pdf  public class TrequeT extends AbstractListT {  .pdf
public class TrequeT extends AbstractListT { .pdf
info30292
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
ecomputernotes
 
Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
Skills Matter
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 
Effective Java - Still Effective After All These Years
Effective Java - Still Effective After All These YearsEffective Java - Still Effective After All These Years
Effective Java - Still Effective After All These Years
Marakana Inc.
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
Baruch Sadogursky
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 

Similar to Java interface and inheritance (20)

14 thread
14 thread14 thread
14 thread
 
Generics
GenericsGenerics
Generics
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
public class TrequeT extends AbstractListT { .pdf
  public class TrequeT extends AbstractListT {  .pdf  public class TrequeT extends AbstractListT {  .pdf
public class TrequeT extends AbstractListT { .pdf
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Effective Java - Still Effective After All These Years
Effective Java - Still Effective After All These YearsEffective Java - Still Effective After All These Years
Effective Java - Still Effective After All These Years
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
My java file
My java fileMy java file
My java file
 
Java file
Java fileJava file
Java file
 

Recently uploaded

Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
scholarhattraining
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Reflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdfReflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdf
amberjdewit93
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 

Recently uploaded (20)

Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Reflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdfReflective and Evaluative Practice...pdf
Reflective and Evaluative Practice...pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 

Java interface and inheritance

  • 1. Java interface and inheritance FOR MORE CLASSES VISIT www.tutorialoutlet.com public interface List<T> { public void add(T item) throws IndexOutOfBoundsException; public T get(int i) throws IndexOutOfBoundsException; public T remove(int i); public int size(); default void println() { System.out.print("["); for (int i = 0; i < size()-1; i++) { System.out.print(get(i) + ","); } if (size() > 0) { System.out.println(get(size()-1) + "]"); } } } ............................................................................................................. public class LinkedList<T> implements List<T> { private class Node<T> { public T value; public Node<T> next; }
  • 2. private Node<T> head; public void add(T item) throws IndexOutOfBoundsException { Node<T> curr = head; if (curr == null) { head = new Node<>(); head.value = item; head.next = null; } else { while (curr.next != null) { curr = curr.next; } curr.next = new Node<>(); curr.next.value = item; curr.next.next = null; } } public T get(int i) throws IndexOutOfBoundsException { if (i < 0 && i >= size()) throw new IndexOutOfBoundsException("Element doesn't exist at location " + i); } Node<T> curr = head; while (i > 0) { curr = curr.next; i--; }
  • 3. return curr.value; public T remove(int i) { if (i < 0 && i >= size()) throw new IndexOutOfBoundsException("Element doesn't exist at location " + i); // Implement } } public int size() { int size = 0; Node<T> curr = head; while (curr != null) { curr = curr.next; size++; } return size; } ........................................................................................... public class Main { public static void testList(List<String> list) { list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.println(); // Should print [a,b,c,d] System.out.println(list.size()); // Should print 4 String second = list.get(2);
  • 4. System.out.println(second); // Should print c list.add("e"); list.add("f"); list.add("g"); list.add("h"); list.add("i"); list.add("j"); list.println(); // Should print [a,b,c,d,e,f,g,h,i,j] try { list.add("k"); // Should throw an error for DumbList but work for LinkedList } catch (IndexOutOfBoundsException e) { System.out.println(e.getMessage()); // Should print You cannot add any more item. Only 10 allowed. for DumbLink } list.remove(0); } list.println(); // Should print [b,c,d,e,f,g,h,i,j] public static void main(String args) { List<String> list = new DumbList<>(); //List<String> list = new LinkedList<>(); } testList(list); } ........................................................................................ ..........
  • 5. class FastLinkedList<T> extends LinkedList<T> { private int size = 0; @Override public void add(T item) throws IndexOutOfBoundsException { //Implement } @Override public T remove(int i) { //Implement } @Override public int size() { return size; } public void prettyPrint() { //Implement } } ....................................................................... public class DumbList<T> implements List<T> { private final int MAX_SIZE = 10; private Object array = new Object[MAX_SIZE]; private int size = 0; public void add(T item) throws IndexOutOfBoundsException {
  • 6. if (size + 1 > MAX_SIZE) { throw new IndexOutOfBoundsException("You cannot add any more item. Only " + MAX_SIZE + " allowed."); } else { // Add implementation goes here } } @SuppressWarnings("unchecked") public T get(int i) throws IndexOutOfBoundsException { return (T) array[i]; } public T remove(int i) { if (i < 0 && i >= size) { throw new IndexOutOfBoundsException("Invalid index, plesae supply a number between 0 and " + this.size); } else { @SuppressWarnings("unchecked") T toBeRemoved = (T) array[i]; // Removal Implementation goes here return toBeRemoved; } } public int size() {