cse144 intermediate programming for industrial engineering lab...

27
CSE144 Intermediate Programming for Industrial Engineering Lab Sessions Session 08 Res. Asst. M. Umut İZER

Upload: others

Post on 15-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

CSE144 Intermediate Programming for Industrial EngineeringLab SessionsSession 08

Res. Asst. M. Umut İZER

Page 2: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Assertionspublic class Test {

static void checkDays(String dayOfWeek){

switch (dayOfWeek) {

case "Sunday": System.out.println("It’s Sunday!");

break;

case "Monday": System.out.println("It’s Monday!");

break;

case "Tuesday": System.out.println("It’s Tuesday!");

break;

case "Wednesday": System.out.println("It’s Wednesday!");

break;

case "Thursday": System.out.println("It’s Thursday!");

break;

case "Friday": System.out.println("It’s Friday!");

break;

case "Saturday": System.out.println("It’s Saturday!");

break;

default: assert false: dayOfWeek + " is invalid day";}

}

public static void main(String args[]) {

checkDays("Monday");

checkDays("Friyay"); }

}

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

2

Page 3: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java io.File Class• The Java.io.File class is an abstract representation of file and directory pathnames.

• Instances may or may not denote an actual file-system object such as a file or a directory. • A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing.• Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

• Some important java.io.File class methods are:1. File(File parent,String child): Creates a new File instance from a parent abstract pathname and a child pathname.

2. File(String pathname): Creates a new File instance by converting the given pathname string into an abstract pathname.

3. File(String parent, String child): Creates a new File instance from a parent pathname string and a child pathname

4. canExecute(): Tests whether the application can execute the file denoted by this abstract pathname.

5. canRead(): Tests whether the application can read the file denoted by this abstract pathname.

6. canWrite(): Tests whether the application can modify the file denoted by this abstract pathname.

7. compareTo(File pathname): Compares two abstract pathnames lexicographically.

8. createNewFile(): Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

9. delete(): Deletes the file or directory denoted by this abstract pathname.

10. deleteOnExit(): Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

11. equals(Object obj): Tests this abstract pathname for equality with the given object.

12. exists(): Tests whether the file or directory denoted by this abstract pathname exists.

13. getAbsolutePath(): Returns the absolute pathname string of this abstract pathname.

14. getCanonicalPath(): Returns the canonical pathname string of this abstract pathname.

15. getName(): Returns the name of the file or directory denoted by this abstract pathname.

16. getParent(): Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

17. getPath(): Converts this abstract pathname into a pathname string.

18. isAbsolute(): Tests whether this abstract pathname is absolute.

19. isDirectory(): Tests whether the file denoted by this abstract pathname is a directory.

20. isFile(): Tests whether the file denoted by this abstract pathname is a normal file.

21. isHidden(): Tests whether the file named by this abstract pathname is a hidden file.

22. list(): Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

23. mkdir(): Ccreates the directory named by this abstract pathname.

24. renameTo(File dest): Renames the file denoted by this abstract pathname.

25. setExecutable(boolean executable): Convenience method to set the owner's execute permission for this abstract pathname.

26. setReadable(boolean readable): Convenience method to set the owner's read permission for this abstract pathname.

27. setReadOnly(): Marks the file or directory named by this abstract pathname so that only read operations are allowed.

28. setWritable(boolean writable): Aa convenience method to set the owner's write permission for this abstract pathname.

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

3

Page 4: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java io.File Class

import java.io.File;

public class FileDemo {

public static void main(String[] args) {File f = null;String[] strs = {"test1.txt", "test2.txt"};try {

// for each string in string array for(String s:strs ) {

// create new filef = new File(s);

// true if the file is executableboolean bool = f.canExecute();

// find the absolute pathString a = f.getAbsolutePath();

// prints absolute pathSystem.out.print(a);

// printsSystem.out.println(" is executable: "+ bool);

} } catch (Exception e) {

// if any I/O error occurse.printStackTrace();

}}

}

4

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 5: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java io.File Class

import java.io.File;

// Displaying file property class fileProperty{

public static void main(String[] args) { //accept file name or directory name through command line argsString fname =args[0];

//pass the filename or directory name to File object File f = new File(fname);

//apply File class methods on File object System.out.println("File name :"+f.getName()); System.out.println("Path: "+f.getPath()); System.out.println("Absolute path:" +f.getAbsolutePath()); System.out.println("Parent:"+f.getParent()); System.out.println("Exists :"+f.exists()); if(f.exists()) {

System.out.println("Is writeable:"+f.canWrite()); System.out.println("Is readable"+f.canRead()); System.out.println("Is a directory:"+f.isDirectory()); System.out.println("File Size in bytes "+f.length());

} }

}

5

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 6: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java io.File Class

import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader;

class Contents { public static void main(String[] args) throws IOException {

//enter the path and dirname from keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter dirpath:"); String dirpath=br.readLine(); System.out.println("Enter the dirname"); String dname=br.readLine(); //create File object with dirpath and dnameFile f = new File(dirpath, dname); //if directory exists,thenif(f.exists()){

//get the contents into arr[] //now arr[i] represent either a File or Directory String arr[]=f.list(); //find no. of entries in the directory int n=arr.length; //displaying the entries for (int i = 0; i < n ; i++) {

System.out.println(arr[i]); //create File object with entry and test if it is a file or directory File f1=new File(arr[i]); if(f1.isFile()) System.out.println(": is a file"); if(f1.isDirectory()) System.out.println(": is a directory"); }

System.out.println("No of entries in this directory "+n); } else System.out.println("Directory not found");

} }

6

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 7: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java PrintWriter Class

• Java PrintWriter class is the implementation of Writer class. It is used to print the formatted representation of objects to the text-output stream.

• Following is the list of Java PrintWriter Class methods.

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

7

Method Description

void println(boolean x) Prints the boolean value.

void println(char[] x) Prints an array of characters.

void println(int x) Prints an integer.

PrintWriter append(char c) Appends the specified character to the writer.

PrintWriter append(CharSequence ch) Appends the specified character sequence to the writer.

PrintWriter append(CharSequence ch, int start, int end) Appends a subsequence of specified character to the writer.

boolean checkError() Flushes the stream and check its error state.

protected void setError() Indicates that an error occurs.

protected void clearError() Clears the error state of a stream.

PrintWriter format(String format, Object... args) Writes a formatted string to the writer using specified arguments and format string.

void print(Object obj) Prints an object.

void flush() Flushes the stream.

void close() Close the stream.

Page 8: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java PrintWriter Class

import java.io.File;

import java.io.PrintWriter;

public class PrintWriterExample {

public static void main(String[] args) throws Exception {

//Data to write on Console using PrintWriter

PrintWriter writer = new PrintWriter(System.out);

writer.write("Industrial Engineering is vital for the businesses.");

writer.flush();

writer.close();

//Data to write in File using PrintWriter

PrintWriter writer1 = null;

writer1 = new PrintWriter(new File("C:\\testout.txt"));

writer1.write("Providing tools such as OR, Quality, VSM etc.");

writer1.flush();

writer1.close();

}

}

8

14

.05

.20

20

CSE

14

4 L

abSe

ssio

n0

8

Page 9: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java Scanner Class• Scanner class in Java is found in the java.util package. Java provides various ways to read

input from the keyboard, the java.util.Scanner class is one of them.• The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by

default. It provides many methods to read and parse various primitive values.• The Java Scanner class is widely used to parse text for strings and primitive types using a

regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.

• The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

• The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0) method which returns a single character.

• To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class. For Example:

Scanner in = new Scanner(System.in);

• To get the instance of Java Scanner which parses the strings, we need to pass the strings in the constructor of Scanner class. For Example:

Scanner in = new Scanner("Hello Java");

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

9

Page 10: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java Scanner Class Methods

• Following is the list of important methods available in the Throwable class.

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

10

SN Method Description

1) close() Closes this scanner.2) delimiter() Gets the Pattern which the Scanner class is currently using to match delimiters.3) findAll() Finds a stream of match results that match the provided pattern string.4) findInLine() Finds the next occurrence of a pattern constructed from the specified string, ignoring

delimiters.5) findWithinHorizon() Finds the next occurrence of a pattern constructed from the specified string, ignoring

delimiters.6) hasNext() Returns true if this scanner has another token in its input.7) hasNextBigDecimal(), hasNextBigInteger(),

hasNextBoolean(), hasNextByte(), hasNextDouble(), hasNextFloat(), hasNextInt(), hasNextLong(), hasNextShort()

Checks if the next token in this scanner's input can be interpreted as a primitive using the nextPrimitive() method or not.

8) hasNextLine() Checks if there is another line in the input of this scanner or not.9) ioException() Gets the IOException last thrown by this Scanner's readable.10) locale() Gets a Locale of the Scanner class.11) match() Gets the match result of the last scanning operation performed by this scanner.12) next() Gets the next complete token from the scanner which is in use.13) nextBigDecimal(), nextBigInteger(), nextBoolean(),

nextByte(), nextDouble(), nextFloat(), nextInt(), nextLong(), nextShort()

Scans the next token of the input as a primitive.

14) nextLine() Gets the input string that was skipped of the Scanner object.15) radix() Gets the default radix of the Scanner use.16) remove() Used when remove operation is not supported by this implementation of Iterator.17) reset() Resets the Scanner which is in use.18) skip() Skips input that matches the specified pattern, ignoring delimiters19) tokens() Gets a stream of delimiter-separated tokens from the Scanner object which is in use.20) toString() Gets the string representation of Scanner using.21) useDelimiter() Sets the delimiting pattern of the Scanner which is in use to the specified pattern.22) useLocale() Sets this scanner's locale object to the specified locale.23) useRadix() Sets the default radix of the Scanner which is in use to the specified radix.

Page 11: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java Scanner Classimport java.util.*;

public class ScannerClassExample {

public static void main(String args[]){

String str = "Hello/This is CSE144 PS/My name is Umut.";

//Create scanner with the specified String Object

Scanner scanner = new Scanner(str);

System.out.println("Boolean Result: "+scanner.hasNextBoolean());

//Change the delimiter of this scanner

scanner.useDelimiter("/");

//Printing the tokenized Strings

System.out.println("---Tokenizes String---");

while(scanner.hasNext()){

System.out.println(scanner.next());

}

//Display the new delimiter

System.out.println("Delimiter used: " +scanner.delimiter());

scanner.close();

}

}

11

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 12: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java Scanner Classimport java.util.*;

import java.util.regex.Pattern;

public class Test {

public static void main(String[] args){

String s = "Hello World! 3 + 3.0 = 6.0 true ";

// create a new scanner with the specified String Object

Scanner scanner = new Scanner(s);

// check if next token is "Hello"

System.out.println("" + scanner.hasNext("Hello"));

// find the last match and print it

System.out.println("" + scanner.match());

// print the line

System.out.println("" + scanner.nextLine());

// close the scanner

scanner.close();

Scanner scanner2 = new Scanner(s);

// skip the word that matches the pattern ..llo

scanner2.skip(Pattern.compile("..llo"));

// print a line of the scanner

System.out.println("" + scanner2.nextLine());

// close the scanner

scanner2.close();

}

}

12

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 13: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java URL Processing

• URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory.

• This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows −

protocol://host:port/path?query#ref

• Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority.

• The following is a URL to a web page whose protocol is HTTP −

http://mimoza.marmara.edu.tr/~umut.izer

• Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80.

• The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses represent the various types of URL connections.

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

13

Page 14: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java URL Class Methods

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

14

Sr.No. Method & Description

1 public String getPath()Returns the path of the URL.

2 public String getQuery()Returns the query part of the URL.

3 public String getAuthority()Returns the authority of the URL.

4 public int getPort()Returns the port of the URL.

5 public int getDefaultPort()Returns the default port for the protocol of the URL.

6 public String getProtocol()Returns the protocol of the URL.

7 public String getHost()Returns the host of the URL.

8 public String getHost()Returns the host of the URL.

9 public String getFile()Returns the filename of the URL.

10 public String getRef()Returns the reference part of the URL.

11 public URLConnection openConnection() throws IOExceptionOpens a connection to the URL, allowing a client to communicate with the resource.

Page 15: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java URL Processingimport java.net.*;

import java.io.*;

public class URLDemo {

public static void main(String [] args) {

try {

URL url = new URL("http://mimoza.marmara.edu.tr/~umut.izer");

System.out.println("URL is " + url.toString());

System.out.println("protocol is " + url.getProtocol());

System.out.println("authority is " + url.getAuthority());

System.out.println("file name is " + url.getFile());

System.out.println("host is " + url.getHost());

System.out.println("path is " + url.getPath());

System.out.println("port is " + url.getPort());

System.out.println("default port is " + url.getDefaultPort());

System.out.println("query is " + url.getQuery());

System.out.println("ref is " + url.getRef());

} catch (IOException e) {

e.printStackTrace();

}

}

}

15

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 16: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java URLConnections Class Methods

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

16

Sr.No. Method & Description

1 Object getContent(): Retrieves the contents of this URL connection.

2 Object getContent(Class[] classes): Retrieves the contents of this URL connection.

3 String getContentEncoding(): Returns the value of the content-encoding header field.

4 int getContentLength(): Returns the value of the content-length header field.

5 String getContentType(): Returns the value of the content-type header field.

6 int getLastModified(): Returns the value of the last-modified header field.

7 long getExpiration(): Returns the value of the expired header field.

8 long getIfModifiedSince(): Returns the value of this object's ifModifiedSince field.

9 public void setDoInput(boolean input): Passes in true to denote that the connection will be used forinput. The default value is true because clients typically read from a URLConnection.

10 public void setDoOutput(boolean output): Passes in true to denote that the connection will be used foroutput. The default value is false because many types of URLs do not support being written to.

11 public InputStream getInputStream() throws IOException: Returns the input stream of the URLconnection for reading from the resource.

12 public OutputStream getOutputStream() throws IOException: Returns the output stream of the URLconnection for writing to the resource.

13 public URL getURL(): Returns the URL that this URLConnection object is connected to.

Page 17: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java URL Processingimport java.net.*;

import java.io.*;

public class URLConnDemo {

public static void main(String [] args) {

try {

URL url = new URL("http://mimoza.marmara.edu.tr/~umut.izer");

URLConnection urlConnection = url.openConnection();

HttpURLConnection connection = null;

if(urlConnection instanceof HttpURLConnection) {

connection = (HttpURLConnection) urlConnection;

}else {

System.out.println("Please enter an HTTP URL.");

return; }

BufferedReader in = new BufferedReader(

new InputStreamReader(connection.getInputStream()));

String urlString = "";

String current;

while((current = in.readLine()) != null) {

urlString += current; }

System.out.println(urlString);

} catch (IOException e) {

e.printStackTrace(); }

}

}

17

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 18: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java Abstract Class• A class which is declared with the abstract keyword is known as an abstract class in Java. It can

have abstract and non-abstract methods (method with the body).• Abstraction is a process of hiding the implementation details and showing only functionality to

the user.• Another way, it shows only essential things to the user and hides the internal details, for example,

sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery.

• Abstraction lets you focus on what the object does instead of how it does it.• There are two ways to achieve abstraction in java

• Abstract class (0 to 100%)• Interface (100%)

• A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

• Points to Remember• An abstract class must be declared with an abstract keyword.• It can have abstract and non-abstract methods.• It cannot be instantiated.• It can have constructors and static methods also.• It can have final methods which will force the subclass not to change the body of the method.

• A method which is declared as abstract and does not have implementation is known as an abstract method.

• Example of abstract methodabstract void printStatus();//no method body and abstract

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

18

Page 19: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java Abstract Classabstract class Shape{

abstract void draw();

}

//In real scenario, implementation is provided

//by others i.e. unknown by end user

class Rectangle extends Shape{

void draw(){System.out.println("drawing rectangle");}

}

class Circle1 extends Shape{

void draw(){System.out.println("drawing circle");}

}

//In real scenario, method is called by programmer or user

class TestAbstraction1{

public static void main(String args[]){

Shape s=new Circle1();

//In a real scenario, object is provided

//through method, e.g., getShape() method

s.draw();

}

}

19

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 20: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java Abstract Class

abstract class Bank{

abstract int getRateOfInterest();

}

class SBI extends Bank{

int getRateOfInterest(){return 7;}

}

class PNB extends Bank{

int getRateOfInterest(){return 8;}

}

class TestBank{

public static void main(String args[]){

Bank b;

b=new SBI();

System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");

b=new PNB();

System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");

}

} 20

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 21: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java Abstract Class

//Example of an abstract class that has abstract and non-abstract methods

abstract class Bike{

Bike(){System.out.println("bike is created");}

abstract void run();

void changeGear(){System.out.println("gear changed");}

}

//Creating a Child class which inherits Abstract class

class Honda extends Bike{

void run(){System.out.println("running safely..");}

}

//Creating a Test class which calls abstract and non-abstract methods

class TestAbstraction2{

public static void main(String args[]){

Bike obj = new Honda();

obj.run();

obj.changeGear();

}

} 21

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 22: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java Abstract Class

// Abstract class

abstract class Animal {

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

System.out.println("Zzz"); }

}

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee"); }

}

class MyMainClass {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

}

}

22

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 23: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Example: Java Abstract Class

// abstract class

abstract class A {

// abstract method, it has no body

abstract void m1();

// concrete methods are still allowed in abstract classes

void m2() {

System.out.println("This is a concrete method."); }

}

// concrete class B

class B extends A {

// class B must override m1() method

// otherwise, compile-time xception will be thrown

void m1() {

System.out.println("B's implementation of m2."); }

}

// Driver class

public class AbstractDemo {

public static void main(String args[]) {

B b = new B();

b.m1();

b.m2();

}

}

23

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

Page 24: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java Interfaces• An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A

class implements an interface, thereby inheriting the abstract methods of the interface.• Along with abstract methods, an interface may also contain constants, default methods, static

methods, and nested types. Method bodies exist only for default methods and static methods.• Writing an interface is similar to writing a class. But a class describes the attributes and behaviors

of an object. And an interface contains behaviors that a class implements.• Unless the class that implements the interface is abstract, all the methods of the interface need to

be defined in the class.• An interface is similar to a class in the following ways −

• An interface can contain any number of methods.• An interface is written in a file with a .java extension, with the name of the interface matching the

name of the file.• The byte code of an interface appears in a .class file.• Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure

that matches the package name.

• However, an interface is different from a class in several ways, including −• You cannot instantiate an interface.• An interface does not contain any constructors.• All of the methods in an interface are abstract.• An interface cannot contain instance fields. The only fields that can appear in an interface must be

declared both static and final.• An interface is not extended by a class; it is implemented by a class.• An interface can extend multiple interfaces.

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

24

Page 25: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java Interfaces• The interface keyword is used to declare an interface. Here is a simple example to declare an interface −

/* File name : NameOfInterface.java */

import java.lang.*;

// Any number of import statements

public interface NameOfInterface {

// Any number of final, static fields

// Any number of abstract method declarations\

}

• Interfaces have the following properties −

• An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface.

• Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

• Methods in an interface are implicitly public.

Example

/* File name : Animal.java */

interface Animal {

public void eat();

public void travel();

}

• When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

• A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

25

Page 26: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

Java Interfaces

• When overriding methods defined in interfaces, there are several rules to be followed

• Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.

• The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.

• An implementation class itself can be abstract and if so, interface methods need not be implemented.

• When implementation interfaces, there are several rules −

• A class can implement more than one interface at a time.

• A class can extend only one class, but implement many interfaces.

• An interface can extend another interface, in a similar way as a class can extend another class.

• The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

• A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

• The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08

26

Page 27: CSE144 Intermediate Programming for Industrial Engineering Lab …mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS8.pdf · 2020-05-15 · Java io.File Class • The Java.io.File class

References

• Liang, Y.D. (2011). PowerPoint Lecture Slides for Introduction to Java Programming, 8th Edition, Georgia Southern University.

• https://www.programiz.com/java-programming/assertions

• https://www.tutorialspoint.com/java/java_file_class.htm

• https://www.geeksforgeeks.org/file-class-in-java/

• https://www.javatpoint.com/java-printwriter-class

• https://www.tutorialspoint.com/java/util/java_util_scanner.htm

• https://www.javatpoint.com/Scanner-class

• https://www.tutorialspoint.com/java/java_url_processing.htm

• www.geeksforgeeks.org/abstract-methods-in-java-with-examples/

• https://www.w3schools.com/java/java_abstract.asp

• https://www.javatpoint.com/abstract-class-in-java

• https://www.tutorialspoint.com/java/java_interfaces.htm27

14

.05

.20

20

CSE

14

4 L

ab S

essi

on

08