Day 7 of 100 - Java: Files scan, OOP concepts
Janardhan Pulivarthi
Posted on January 15, 2022
Input scanner
import java.util.Scanner;
//
System.out.println("Enter your name: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Your name is: " + name);
For scanning files
File file = new File("phone_numbers.txt");
Scanner fileScanner = new Scanner(file);
Reading an ebook text file, project link https://github.com/j143/wordcount-java
Errors
Common runtime errors are formalized into something called Exceptions.
Example, FileNotFoundException
.
Use throws
keyword.
try {
openFile("file.txt");
} catch (FileNotFoundException e) {
// Handle the exception
System.out.println("File is not available!");
}
// catch(IndexOutOfBoundsException e) {
//
// }
//
Inheritance
Bank account manager
Three different accounts, different account number, balances, limit types
class BankAccount {
int accountType;
String accountNumber;
double balance;
double limit;
int transfers;
Date expiry;
}
in place of the above code
class BankAccount {
String accountNumber;
double balance;
}
class COD extends BankAccount {
Date expiry;
}
Polymorphism
Student student = new Student();
Teacher teacher = new Teacher();
//
// or
Person student = new Student();
Person teacher = new Teacher();
Bag and contents example
public class Bag {
int currrentWeight;
boolean canAddItem(Item item);
}
Override
When a class extends a parent class, all public methods declared in the parent class are automatically included in the child class. We are allowed to override any of those methods. Overriding means re-declaring them in the child class and then redefining what they should do.
Super
Re-use the parent method in the child class by using super
keyword, followed by a dot and method name.
Interface
Its defines what needs to be done, but now how to do it. Include the methods needed but cannot implement method.
A Class can be inherited by more than one class.
Example, Caravan which is a bus + house
public interface Movable{
void move(int distance);
boolean canMove();
}
public interface Habitable {
boolean canFit(int inhabitants);
}
public class Caravan implements Habitable, Movable {
void move(int distance) {
location = location + distance;
}
boolean canFit(int inhabitants) {
return max <= inhabitants;
}
}
Posted on January 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.