Java I Basics 9 OOP [A]
Java Basics
Java Basic 1: Intro
- Intellij shortcut: Ctrl+J
- JavaSE Basic ; JavaME Mobile; JavaEE Web
- Install JDK; jdk1.8; jdk-9
- set path name: JAVA_HOME: C:\Program Files\Java\jdk-9
- set environment path: %JAVA_HOME%\bin; or all users: C:\Program Files\Java\jdk-9\bin;
- cmd: java -version
- Create file testJ
class testJ {
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
- run testJ
C:\Users\Administrator>cd D:\testJ
D:\test>javac testJ.java
D:\test>java testJ helloworld hello
Your first argument is: helloworld
- \n: return \t: tab
System.out.print("Your\t first\t argument\t is: \n"+args[0]);
Your first argument is:
hello
- install myEclipse: create a Java Project: set Workspace
- set JRE: buildpath: configure buildpath: path for jdk
- alt+/: shortcut for main, sysout : Window>Preferences>Java>Editor>Templates
- // /** */ /**/ comments
Java Basic 2: Data Type & Operators
-
heap memory: 10; 10.0
-
stack memory: int x=10; double d=10.0;
-
String CharArray
-
byte 8bit, short 16bit, int 32bit, long 64bit: Integer
-
float 32bit, double 64bit: Float
-
char 8bit: Character
-
true, false, null: Boolean
-
0b {0,1} binary; 0 {0…7} octal ; {0…9} decimal ; 0x{0…9,a…f} hex;
System.out.println(0b100);//binary 2^2 =4
System.out.println(0100);//octal 8^2 =64
System.out.println(100);//dec 10^2 =100
System.out.println(0x100);//hex 16^2 =256
- class, interface, void, if, else, switch, case, default, while, do, for, break, continue, return
- final
final int NUM_UP =10; //final marks constant
- Scanner
- String val= sc.next(); String val= sc.nextLine();
- double val=sc.nextDouble(); int val=sc.nextInt();
- Boolean val=sc.hasNext();
import java.util.Scanner; //import scanner
public class ScannerTest {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int i= sc.nextInt(); //Integer
System.out.println(i);
Scanner sc2= new Scanner(System.in);
String line= sc2.nextLine(); //String
System.out.println(line);
sc.close();
sc2.close();
}
}
- calculations
- */±%; ++, --; +=, -=, *=, /=, %=
- boolean: ==, !=, <,>,<=,>=, instanceof
- logic: && and , || or, ! not, ^ xor, execute all: & , I
- bit calc: &, I, ^,~, <<,>>,>>>
System.out.println(10/3);//3
int a=10;
int b=(a++)+(++a);//calcfirst + incrementfirst
System.out.println(a);//12
System.out.println(b);//22
System.out.println(a+=1);//13
System.out.println(a%=2);//1
System.out.println(3 & 4);// 011 & 100 =0
System.out.println(3 | 4);// 011 | 100 =7
System.out.println(3 ^ 4);// 011 ^ 100 =7
System.out.println(~ 3);// 011 = 100 = -4
System.out.println(64 >> 4);// 1,000,000 = 100 =4
System.out.println(64 << 4);//1,000,000 = 10,000,000,000 =1024
- (Boolean)? choiceTrue: choiceFalse
int x=23;
int y=20;
int z=24;
int k= (y>x)?y:(x>z)?x:z;
System.out.println(k);//get large num=24
System.out.println("enternum:");
Scanner sc= new Scanner(System.in);
int testmod=sc.nextInt();
String str= (testmod%2 == 0)?"Even":"Odd";
System.out.println(str); //even Odd
Java Basic 3: Flow
- Math.random()
double d= Math.random();
double d2= Math.random()*10; //[0,10)
int x= (int)d2;
System.out.println("d: "+d+" d2: "+d2+" x: "+x);
- if, switch, for , while, return
//if
double money = 100.00;
if (money>50){
System.out.println("steak");
}else if(money<10){
System.out.println("soup");
}else{
System.out.println("sandwich");
}
//use ?:
String dinner= (money>50)?"steak":(money<10)?"soup":"sandwich";
System.out.println("?:"+ dinner);
//switch: int byte short char enum String
System.out.println("enter 1-4: ");
Scanner sc= new Scanner(System.in);
int season=sc.nextInt();
switch(season){
case 1:
System.out.println("Spring");
break;
case 2:
System.out.println("Summer");
break;
case 3:
System.out.println("Fall");
break;
case 4:
System.out.println("Winter");
break;
default:
System.out.println("wrong entry");
}
//for
for(int i=1; i<=5; i++){
System.out.print("i"+ i+" ");
for(int j=1; j<=10; j++){
if (i%2==0){
break;
}
System.out.print("j"+ j+" ");
}
System.out.println(" ");
}
//for Armstrong num narcissistic num
int a=0;
int b=0;
int c=0;
for (int i=100; i<1000; i++){
a=i/100;//100
b=(i%100)/10;//10
c=(i%100)%10;
if(i==a*a*a+b*b*b+c*c*c){
System.out.println(i);
}
}
//while(condition) {...}
int i=0;
while(i<5){
System.out.println("Hello:"+i);
i++;
}
//do{...} while(condition)
- break, continue, return
for(int i=0; i<10; i++)//break, stops loop
{
if (i>5) break;
System.out.print(i);
}
System.out.println("\n");
for(int i=0; i<10; i++)//while, jump out of current loop
{
if (i==5) continue;
System.out.print(i);
}
System.out.println("\n");
//break at certain points
loopOut: for(int i=1; i<10; i++){
loopIn: for(int j=1; j<=i; j++){
if (j==3){
break loopOut;
}
System.out.print(i+"*"+j+"="+i*j+"\t");
}
System.out.println();
}
System.out.println("\n");
//return at certain points
loopOut: for(int i=1; i<10; i++){
loopIn: for(int j=1; j<=i; j++){
if (i%2==0){
//break loopIn;
return; //ends entire program
}
System.out.print(i+"*"+j+"="+i*j+"\t");
}
System.out.println("\n");
}
Java Basic 4: Array
- Array must be same data type
- int[] arr = new int[10];
- int[] arr = {1,2,3,4,5};
- int[][] arr = new int[10][10];
- int[][] arr = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
int[] arr= new int[5];
System.out.println(arr);//[I@2a139a55 (arr address in stack,
//also address in heap with array values in heap)
for(int x: arr){
System.out.println(x);//0
}
//everything with "new" stored in heap, which has initial value
//String= null
//Boolean= false
//char=\u0000 (space)
int [][] arr2= new int[3][2];
System.out.println(arr2);
for(int[] arrx: arr2){
System.out.println(arrx);
for(int x: arrx){
System.out.print(x);
}
System.out.println();
}
- Pascal’s triangle
public class pascalTriangle {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int row= sc.nextInt();
//define height
int[][] tri= new int[row+1][];
tri[0]= new int[1];
tri[1]= new int[1+2];
tri[1][1]=1;
//insert value
for(int i=2; i<=row;i++){
tri[i]=new int[i+2];
for(int j=1; j<tri[i].length-1; j++){
tri[i][j]=tri[i-1][j-1]+tri[i-1][j];
}
System.out.println();
}
//output
int len=tri.length;
for(int i=0; i<tri.length;i++){
while(len>=i){
System.out.print(" ");
len--;
}
for(int j=0; j<tri[i].length; j++){
if(i==0)
System.out.print(" ");
System.out.print(tri[i][j]+" ");
}
System.out.println();
len=tri.length;
}
}
}
Java 9
- install jdk9 from oracle
- add environment path: C:\Program Files\Java\jdk-9\bin
D:\test>java -version
java version "9"
Java(TM) SE Runtime Environment (build 9+181)
Java HotSpot(TM) 64-Bit Server VM (build 9+181, mixed mode)
- module: create directory for lib and mods
- create new project for java 9; create directory under src as com.abc.module
- new: module-info under com.abc.module: module com.abc.module{}
module com.abc.module {
// requires com.abc.module.HelloModule;
// exports com.abc.module.HelloModule;
}
- create java test file under com.abc.module inside new directory com.abc.module
package com.abc.module.com.abc.module;
public class HelloModule {
public static void main(String[] args) {
System.out.println("Hello Module!");
//get name of module
Module mod=HelloModule.class.getModule();
String modName=mod.getName();
System.out.println("Module Name: "+ modName);
System.out.format("Module Name: %s%n", modName);//formatted
}
}
- use javac to run module
D:\MyEclipseWorkspace\java9>javac -d mods --module-source-path
src -encoding UTF-8
src\com.abc.module\module-info.java
src\com.abc.module\com\abc\module\HelloModule.java
- new directory created under mods -d mods
D:\MyEclipseWorkspace\java9>jar --create --file lib/mymodule-1.0.jar
--main-class com.abc.module.com.abc.module.HelloModule
-C mods\com.abc.module .
- -C mods\com.abc.module name in module-info
- . under current directory
- jar file created, run module, package name repeated …
D:\MyEclipseWorkspace\java9>java --module-path lib --module com.abc.module/com.a
bc.module.com.abc.module.HelloModule
Hello Module!
Module Name: com.abc.module
Module Name: com.abc.module
- JShell
C:\>Jshell
| 欢迎使用 JShell -- 版本 9
| 要大致了解该版本, 请键入: /help intro
- Processing ID
module com.abc.module {
requires java.management; //must add when import class
}
import java.lang.management.ManagementFactory;
//older method
public class GetPID {
public static void main(String[] args) {
//Runtime.getRuntime().exe
String name= ManagementFactory.getRuntimeMXBean().getName();
System.out.println(name);
String pid = name.split("@")[0];
System.out.println("PID:"+pid);
}
}
public class GetPID2 { //easier pid
public static void main(String[] args) {
ProcessHandle ph= ProcessHandle.current();
long pid=ph.pid();
System.out.println("PID: "+pid);
}
}
- private method in Interface
public class PrivateInterface {
void show(){//java8
System.out.println("show Info");
print();
}
private void print(){
System.out.println("private method in interface");
}
}
- Collection
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MyCollection {
public static void main(String[] args) {
//list
List<String> list= List.of("hello","world");
System.out.println(list);
//map
Map<String,Integer> map=Map.of("num",1,"num2",200);
System.out.println(map);
//set
Set<String> set= Set.of("blue","red","corn");
System.out.println(set);
}
}
- Http: PROBLEMATIC !!! java.lang.NoClassDefFoundError: jdk/incubator/http/HttpClient !!!
import java.io.IOException;
import java.net.URI;
public class MyHttpClient {
public static void main(String[] args) {
HttpClient hc = HttpClient.newHttpClient();
//create HttpRequest
HttpRequest req=HttpRequest.newBuilder(URI.create("http://www.bing.com")).GET().build();
try{
HttpResponse<String> resp= hc.send(req, HttpResponse.BodyHandler.asString());
System.out.println(resp);
String respBody = resp.body();
System.out.println(respBody);
}catch (IOException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
Java OOP
Java OOP 1: Class & Object
- class variables: age, weight
- class methods: live, eat, wear
- one public class per .java file
- Stack Memory is used for static memory allocation and the execution of a thread. It contains primitive values and references to objects that are in a heap, specific to the method. A block is created in a stack when the method is invoked to hold the values and object reference of the methods. After the execution of a method, the block is available for the next method. -XSS (java.lang.StackOverFlowError)
- Heap space is used for dynamic memory allocation for Java objects and JRE classes at the runtime including constant and string pool (not processed by garbage). Objects accessed globally. -Xms and -Xmx ( java.lang.OutOfMemoryError)
public class Visitor {
String name;
int age;
public void bookTicket() {
if (age>=20){
System.out.println("ticket: $20");
}else{
System.out.println("ticket: $10");
}
}
}
class VisitorTest{
public static void main(String[] args) {
String name="";
do{
Scanner sc= new Scanner(System.in);
System.out.println("enter name (x to exit): ");
name= sc.nextLine();
if("x".equals(name)){
System.out.println("goodbye!");
break;
}
System.out.println("enter age: ");
int age= sc.nextInt();
//create object
Visitor v=new Visitor();
v.name=name;
v.age=age;
v.bookTicket();
}while(!"x".equals(name));
}
}
- Method: blackbox
- static methods does not need an object to execute
- static methods and parameters called by directly using static class name
- static parameter and methods must be called from a static method
public class Calc {
public static void main(String[] args) {
sum();//static call
int sum=Calc.sum(); //get static return value
Calc c= new Calc(); //regular method need an obj
c.add(); //regular call
sum=c.add();//get value
}
static int sum(){
System.out.println("20+10= "+20+10);
return 20+10;
}
int add(){
System.out.println("20+30= "+20+30);
return 20+30;
}
}
- Eclipse: Source/auto-generate getter setter toString
- this: give parameters to constructors
- toString: replace object location with parameters
- constructor overload, return type different does not count
public class BookTest {
public static void main(String[] args) {
Book book1= new Book("bookName");
Book book2= new Book("bookName2");//static constructors and methods
//do not get called a second time
}
}
class Book{
String name;
Person p1= new Person(1);//constructor third
public Book(String name){
this.name=name;
System.out.println(name); //method fourth
}
Person p2=new Person(2);//constructor third
static Person p3= new Person(3);//static constructor processed first
//Anonymous static method
static{
System.out.println("Static Anonymous method"); //static method second
}
}
class Person{
public Person(int num){
System.out.println("myPerson"+num);
}
}
Java OOP 2: Encapsulation & Inheritance
- encapsulation: keep parameters private in a class, clean up input
- getter/setter, private parmaters
public class Dog {
private String name;
private String furColor;
private int age;
public Dog(){}
public Dog(String name, String furColor, int age) {
super();
this.name = name;
this.furColor = furColor;
this.age = age;
}
//method
public void run(){
System.out.println(furColor+ " "+name+" running ...");
}
public int getAge() {
return age;
}
public void setAge(int age) {
//provide condition
if(age<1 || age>100){
System.out.println("age wrong");
}else
this.age = age;
}
}
class DogTest{
public static void main(String[] args) {
//create object
Dog dog=new Dog("Happy","pink",3);
System.out.println(dog.getAge());
dog.run();
//
}
}
- javaBean
public class JavaBean {
private int id;
private String userName;
private String password;
private String address;
public JavaBean(){}
public JavaBean(int id, String userName, String password, String address) {
super();
this.id = id;
this.userName = userName;
this.password = password;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
- package imported, name backwards ie: com.abc.pack
- common packages: java.lang; java.util; java.io;
- packages can be directly referred to under the same project src file
com.bf.javaOop.Student stu3= new Student();
- access modifier: public (all), private (class), ~nothing (class, package), protected(class, package, children)
- static method should not call non static method,
- static used to declare constants
public class StaticTest {
static int age; //static variable
static { //static method anonymous
System.out.println("before age: "+age);//0
age=12;
System.out.println("after age: "+age);//12
}
public static void main(String[] args) {
age+=10;
System.out.println("age:"+age);//22
StaticTest.method(15); //static call
method(25); //static call
}
public static void method(int num){ //static method
System.out.println("num: "+num);//15 //25
age+=5;
System.out.println("age:"+age);//27 //32
}
}
public class Voter {
//when vote gets to 100 stop
static int count;
String name;
static final int TOTAL= 100;
Voter(){}
Voter(String name){
this.name=name;
}
//vote
public static void vote(){
if(count>=TOTAL)
System.out.println("Voting Ends");
else
count++;
}
//show count
public void showCount(){
System.out.println(this.name+" Vote Count: "+count);
}
}
class TestVote{
public static void main(String[] args) {
Voter v1= new Voter();
for(int i=1; i<101; i++){
v1= new Voter("Blob"+i);
Voter.vote();
}
v1.showCount();
}
}
-
Inheritance Extends : only write repeated methods once
-
children classes can only have one parent
-
Child class use super to refer to parent parameters
public class Student extends Human{
private String[] names= new String[3];
public Student(){
System.out.println("no parameter constructor");
}
public Student(String name, int age){
super(name, age);
}
public void study(){
System.out.println("Student Studying...");
}
public void add(){
getNames()[0]="Monkey";
getNames()[1]="Puppy";
getNames()[2]="Turtle";
}
public void search(int start, int end){
for(int i=start-1; i<end; i++){
String name= getNames()[i];
System.out.println(name);
}
}
@Override
public String toString() {
return "Student [name=" + super.name + ", age=" + super.age + "
, names=" + Arrays.toString(getNames()) + "]";
}
public String[] getNames() {
return names;
}
public void setNames(String[] names) {
this.names = names;
}
}
class Teacher extends Human{
Teacher(String name, int age) {
super(name, age);
// TODO Auto-generated constructor stub
}
public void study(){
System.out.println("Teacher is Sleeping...");
}
}
class StuTest{
public static void main(String[] args) {
Student stu= new Student();
Human stu2= new Student("Bambi",33);
Human t1= new Teacher("Bob",44);
t1.study();
System.out.println(stu2.name);
stu.add();
System.out.println(stu2);//use toString
System.out.println(stu);//if no toString then return location
System.out.println(stu.getNames().length);
//find student names 2~3
stu.search(2, 3);
com.bf.javaOop.Student stu3= new Student();
}
}
- parent class
public class Human {
String name;
int age;
Human(){}
Human(String name, int age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void study() {
// TODO Auto-generated method stub
}
}
- inheritance
public class inheritTest {
public static void main(String[] args) {
A t=new A("Blob");
t.show();
A t2=new A();
t2.show();
}
}
class A extends B{
A(){
System.out.println("Child A");
}
A(String name){
super("BlobParent");
System.out.println("Child A "+name);
}
void show(){
System.out.println(this.num); //refer to num in B
System.out.println(this.addr); //refer to addr in C
}
}
class B extends C{
B(){
System.out.println("Parent 1 gen B");
}
B(String name){
super("BlobGrandParent");
System.out.println("Parent 1 gen "+name);
}
int num=10;
}
class C{
String name;
C(){
System.out.println("Parent 2 gen C");
}
C(String name){
this.name=name;
System.out.println("Parent 2 gen "+name);
}
String addr="Island";
}
Java OOP 3: Inheritance & Polymorphism
public class Pet {
private String name;
private int health;
private int love;
private String gender;
public Pet(String name, int health, int love, String gender) {
super();
this.name = name;
this.health = health;
this.love = love;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getLove() {
return love;
}
public void setLove(int love) {
if (love>100||love<0 )
this.love=60;
else
this.love = love;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public void show(){
System.out.println("name: "+name+" health: "+health+" love: "+love+" gender: "+gender);
}
}
class Penguin extends Pet{
public Penguin(String name, int health, int love, String gender) {
super(name, health, love, gender);
// TODO Auto-generated constructor stub
System.out.println("Penguin");
}
}
class Cat extends Pet{
public Cat(String name, int health, int love, String gender) {
super(name, health, love, gender);
System.out.println("Cat!");
// TODO Auto-generated constructor stub
}
}
class TestPet{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter name: ");
String name=sc.next();
System.out.println("enter gender: ");
String gender=sc.next();
System.out.println("enter love: ");
int love=sc.nextInt();
System.out.println("enter health: ");
int health=sc.nextInt();
System.out.println("enter type of animal: (1 Cat 2 Penguin)");
int type=sc.nextInt();
switch (type){
case 1:
Pet p=new Cat(name, health, love, gender);
p.show();
break;
case 2:
Pet p1=new Penguin(name, health, love, gender);
p1.show();
break;
}
}
}
- Method Overload: same name return type and parameter does not matter
- Method Override: child cannot include parameters or return types more specific than parents ie: toString
- java.lang.Object: parent of all classes methods {clone equals finalize getClass hashCode notify notifyAll toString wait}
- Obj comparison need to override hashCode() and equals()
- boolean= obj instanceof class
public class myObj {
public static void main(String[] args) {
Obj o= new Obj();
int hc;
System.out.println("hashcode: "+(hc=o.hashCode())); //return hashcode
System.out.println(o.toString()); //return obj location in Hex
//toString getClass().getName()+"@"+Integer.toHexString(hashCode())
System.out.println(o.getClass()); //return class name
System.out.println(o.getClass().getPackage()); //return package name
Obj o1= new Obj("Blob",5);
Obj o2= new Obj("Blob",3);
System.out.println(o1.toString()); //return obj location in Hex
System.out.println(o2.toString()); //return obj location in Hex
System.out.println(o1==o2);//false
System.out.println(o1.equals(o2));//false
o2.setId(5);
System.out.println(o1.toString()); //return obj location in Hex
System.out.println(o2.toString()); //return obj location in Hex
System.out.println(o1==o2);//false, different obj
System.out.println(o1.equals(o2));//true
o2=o1;
System.out.println(o1.toString()); //return obj location in Hex
System.out.println(o2.toString());
System.out.println(o1==o2);//true
System.out.println(o1.equals(o2));//true
System.out.println("o2 instanceof Obj: "+(o2 instanceof Obj));
}
}
class Obj{
private String name;
private int id;
public Obj(String string, int id) {
// TODO Auto-generated constructor stub
this.name=name;
this.id=id;
}
public Obj() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Obj o=(Obj)obj;
if((this.name==o.name)&&(this.id==o.id))
return true;
return false;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return id;
}
}
- Polymorphism: example black white printer cannot print color, color printer can print black white
- child can be cast to parent, parent cannot be cast to child
public class Feed {
public static void main(String[] args) {
Feeder f= new Feeder();
Friend fr= new Friend("Buddy");
Friend a= (Friend)new Animal("Bear");
Friend r= new Rock("Blob");
f.feeding(fr);
fr.feel();
f.feeding(a);
a.feel();
f.feeding(r);
r.feel();
}
}
class Feeder{
Friend f;
void feeding(Friend f){
this.f=f;
System.out.println("feeding "+f.getName()+" "+f.getClass().getSimpleName());
}
}
class Animal extends Friend{
Animal(String name){
super(name);
}
void feel(){
System.out.println("feels Full!");
}
}
class Rock extends Friend{
Rock(String name){
super(name);
}
void feel(){
System.out.println("feels Not much!");
}
}
class Friend{
private String name;
Friend(){}
Friend(String name){
this.setName(name);
}
void feel(){
System.out.println("Alien!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- Polymorphism
public class Shop {
public static void main(String[] args) {
Goods tv= new TV("Sony",3000);
Goods f= new Foods("Cheese",30);
tv.print();
f.print();
}
}
class Goods{
private String name;
private double price;
Goods(){}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
void print(){
System.out.println(getName()+" $ "+getPrice());
}
}
Java OOP 4: Abstract & Interface
- Abstract class : use abstract: can have non abstract methods: cannot be instantiated: must use child class to instantiate
- use static methods for calling in abstract method
- Abstract method: no body; abstract method inside abstract class
- non abstract child class must implement all methods in abstract parent class or must be abstract too
- extends abstract class: for inheritance
public abstract class Pet2 {
public abstract void show();
public static void print(){
System.out.println("Parent abstract class");
}
}
class Bird extends Pet2{
public static void show2(){
System.out.println("static class");
}
@Override
public void show() {
// TODO Auto-generated method stub
System.out.println("Child class implement method");
}
}
class TestPet2{
public static void main(String[] args) {
Bird.show2();
Pet2.print();
Bird b=new Bird();
b.show();
}
}
- interface use implement, class can have multiple interfaces (interface1, interface2)
- interface has abstract methods , cannot be private
- cannot be instantiated, must use child class to instantiate, express functions
- all fields are static final public in interface, extends…implement
- start interface with I+myInterface
public interface myInterface {
public void fly();
public final static int SPEED=10;
}
class Bug implements myInterface{
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("flying"+SPEED);
}
}
class TestMyInt{
public static void main(String[] args) {
myInterface b=new Bug();
b.fly();
}
}
public interface Lock {
public void lock();
public void unlock();
}
abstract class Door {
public abstract void open();
public abstract void close();
}
class TheftProofDoor extends Door implements Lock {
@Override
public void open() {
// TODO Auto-generated method stub
System.out.println("OPEN");
}
@Override
public void close() {
// TODO Auto-generated method stub
System.out.println("CLOSE");
}
@Override
public void lock() {
// TODO Auto-generated method stub
System.out.println("LOCK");
}
@Override
public void unlock() {
// TODO Auto-generated method stub
System.out.println("UNLOCK");
}
}
class testLock {
public static void main(String[] args) {
Door door = new TheftProofDoor();
door.close();
TheftProofDoor tpDoor = (TheftProofDoor) door;
tpDoor.lock();
tpDoor.unlock();
door.open();
}
}
- interface
public interface IUsb {
public void service();
}
class Fan implements IUsb{
@Override
public void service() {
// TODO Auto-generated method stub
System.out.println("Fan running...");
}
}
class Usb implements IUsb{
@Override
public void service() {
// TODO Auto-generated method stub
System.out.println("Usb running...");
}
}
class testIUsb{
public static void main(String[] args) {
IUsb fan=new Fan();
IUsb usb=new Usb();
fan.service();
usb.service();
}
}
public interface Iink{
public String getColor();
}
class Color implements Iink{
@Override
public String getColor() {
// TODO Auto-generated method stub
return "Color";
}
}
class BlackWhite implements Iink{
@Override
public String getColor() {
// TODO Auto-generated method stub
return "Black White";
}
}
interface Ipaper{
public String getPaper();
}
class A4 implements Ipaper{
@Override
public String getPaper() {
// TODO Auto-generated method stub
return "A4";
}
}
class B5 implements Ipaper{
@Override
public String getPaper() {
// TODO Auto-generated method stub
return "B5";
}
}
class Printer {
public void print(Iink i, Ipaper p ){
if ((i.getColor().equals("Color"))&& (p.getPaper().equals("A4"))){
System.out.println("use "+i.getColor()+" ink "+p.getPaper()+" paper");
}
else if((i.getColor().equals("Black White")) && (p.getPaper().equals("B5"))){
System.out.println("use "+i.getColor()+" ink "+p.getPaper()+" paper");
}else
System.out.println("Incorrect parameters");
}
}
class testPrinter{
public static void main(String[] args) {
Printer p= new Printer();
Iink ic= new Color();
Iink ib= new BlackWhite();
Ipaper icp= new A4();
Ipaper ibp= new B5();
p.print(ic, icp);
p.print(ib, ibp);
}
}
public abstract class Phone {
private String brand;
private String type;
public Phone (){}
public Phone(String brand, String type) {
this.brand = brand;
this.type = type;
}
public abstract void sendInfo();
public abstract void call();
public void info(){
System.out.println(brand+" "+type);
}
}
interface IPlayMusic{
public void play(String music);
}
interface IPicture{
public void picture();
}
interface INet{
public void net();
}
class RegPhone extends Phone implements IPlayMusic{
RegPhone(){}
RegPhone(String brand, String type) {
// TODO Auto-generated constructor stub
super(brand, type);
}
@Override
public void sendInfo() {
// TODO Auto-generated method stub
System.out.println("Send Text");
}
@Override
public void call() {
// TODO Auto-generated method stub
System.out.println("Send Call");
}
@Override
public void play(String music) {
// TODO Auto-generated method stub
System.out.println("Play "+music);
}
}
class SmartPhone extends RegPhone implements IPicture, INet{
SmartPhone (){}
SmartPhone(String brand, String type){
super(brand,type);
}
@Override
public void net() {
// TODO Auto-generated method stub
System.out.println("Connect to Net");
}
@Override
public void picture() {
// TODO Auto-generated method stub
System.out.println("Take Pic");
}
}
class testCall{
public static void main(String[] args) {
Phone sm= new SmartPhone("HTC","I0000");
sm.info();
sm.call();
sm.sendInfo();
SmartPhone sm2=(SmartPhone)sm;
sm2.play("music");
sm2.net();
sm2.picture();
}
}
public class Computer {
public void show(ICPU cpu, IRAM ram, IHardDisk hd){
System.out.println("CPU Brand " + cpu.getBrand()+ " Freq "+cpu.getFrequency()+"GHz");
System.out.println("RAM "+ ram.getCapacity()+" GB ");
System.out.println("Hard Disk "+ hd.getCapacity()+" TB");
}
}
interface ICPU{
public String getBrand();
public float getFrequency();
}
interface IRAM{
public int getCapacity();
}
interface IHardDisk{
public int getCapacity();
}
class IntelCPU implements ICPU {
@Override
public String getBrand() {
// TODO Auto-generated method stub
return "Intel";
}
@Override
public float getFrequency() {
// TODO Auto-generated method stub
return 3.8f;
}
}
class WDHD implements IHardDisk{
@Override
public int getCapacity() {
// TODO Auto-generated method stub
return 1;
}
}
class JSD implements IRAM{
@Override
public int getCapacity() {
// TODO Auto-generated method stub
return 4;
}
}
class TestComputer{
public static void main(String[] args) {
Computer c=new Computer();
ICPU intel= new IntelCPU();
IHardDisk wdhd=new WDHD();
IRAM jsd=new JSD();
c.show(intel,jsd, wdhd);
}
}
Java OOP 5: Exception
- Exception: can run, example: x/0; java.lang.ArithmeticException:/by zero
- Error: ex: typo ,cannot run
- try{…}catch(Exception.e){e.printStackTrace();}finally{…}
public class testException {
public static void main(String[] args) {
int result= new testException().div(19, 0);
System.out.println("RESULT "+result);
}
public int div(int num1, int num2){
try{
result =num1/num2;
}catch(Exception e){ //System.exit(1) with error //System.exit(0) proper
e.printStackTrace();
System.err.println("Caught Exception");
System.err.println(e.getMessage);
}finally{
System.out.println("div performed");
}
return result;
}
}
- java.lang.Exception, if caught by parent Exception then children are not executed
- System.err.println(“exception message”);
- System.err.println(e.getMessage);
- ArithmeticException, ArrayIndexOutofBoundsException, NullPointerException, ClassNotFoundException, ClassCastException, NumberFormatException, IllegalArgumentException
- finally executed regardless where return is
- check exception from bottom up
public class testSubject {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("1-3");
try{
int no=sc.nextInt();
switch(no){
case 1:
System.out.println("Java");
break;
case 2:
System.out.println("C");
break;
case 3:
System.out.println("Python");
}
}catch (Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}finally{
System.out.println("End");
}
}
}
- throws multiple Exception class used by method
- myException extends Exception create constructors from parent
- class method throws myException throw new myException (no try catch needed)
- main method also throws myException when using class method
- use try catch when main method does not throws myException, e.getmessage
public class myException extends Exception{
public myException() {
super();
// TODO Auto-generated constructor stub
}
public myException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public myException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public myException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public myException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
class UserRegister{
void register(String username) throws myException{
if("admin".equals(username)){
throw new myException("User exist");
}else
System.out.println("successful: "+username);
}
public static void main(String[] args) throws myException {
UserRegister u= new UserRegister();
u.register("Bob");
u.register("admin");
}
}
- RuntimeException: {AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DataBindingException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, FileSystemAlreadyExistsException, FileSystemNotFoundException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, IllformedLocaleException, ImagingOpException, IncompleteAnnotationException, IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MirroredTypesException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NoSuchMechanismException, NullPointerException, ProfileDataException, ProviderException, ProviderNotFoundException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeConstraintException, TypeNotPresentException, UndeclaredThrowableException, UnknownEntityException, UnmodifiableSetException, UnsupportedOperationException, WebServiceException, WrongMethodTypeException}
public class ClothException extends RuntimeException {
public ClothException() {
super();
// TODO Auto-generated constructor stub
}
public ClothException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public ClothException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public ClothException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public ClothException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
class TestCloth{
public static void main(String[] args) {
TestCloth t= new TestCloth();
t.buy(30000);
}
public void buy(int size){
// if (size<0 || size>300){
// throw new ClothException("Wrong size");
// }
try{
if(size<0 || size>300){
throw new ClothException("Wrong size");
}
}catch (ClothException e){
System.out.println(e.getMessage());
}
}
}
public class Child {
public String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) throws ChildException {
if(age<1 || age>=18){
throw new ChildException("child between age 1~17");
}
this.age = age;
}
}
class ChildException extends RuntimeException{
public ChildException() {
super();
// TODO Auto-generated constructor stub
}
public ChildException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public ChildException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public ChildException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public ChildException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
class TestChild{
public static void main(String[] args) {
Child c=new Child();
try{
c.setAge(29);
}catch(ChildException e){
System.out.println(e.getMessage());
}
}
}
Java OOP 6: Exercise
- zoo
public abstract class Zoo {
private String name;
private int legs;
public Zoo() {
}
public Zoo(String name, int legs) {
super();
this.name = name;
this.legs = legs;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLegs() {
return legs;
}
public void setLegs(int legs) {
this.legs = legs;
}
public abstract String Noise();
}
class Chicken extends Zoo {
public Chicken() {
super();
// TODO Auto-generated constructor stub
}
public Chicken(String name, int legs) {
super(name, legs);
// TODO Auto-generated constructor stub
}
@Override
public String Noise() {
// TODO Auto-generated method stub
return "coockooo";
}
}
class Octopus extends Zoo {
public Octopus() {
super();
// TODO Auto-generated constructor stub
}
public Octopus(String name, int legs) {
super(name, legs);
// TODO Auto-generated constructor stub
}
@Override
public String Noise() {
// TODO Auto-generated method stub
return "...";
}
}
class Dolphin extends Zoo {
public Dolphin() {
super();
// TODO Auto-generated constructor stub
}
public Dolphin(String name, int legs) {
super(name, legs);
// TODO Auto-generated constructor stub
}
@Override
public String Noise() {
// TODO Auto-generated method stub
return "eeee";
}
}
class ZooException extends RuntimeException {
public ZooException() {
super();
// TODO Auto-generated constructor stub
}
public ZooException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public ZooException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public ZooException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public ZooException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
class testZoo {
public void display(Zoo[] z) {
int quit = 1;
// TODO Auto-generated method stub
for (Zoo zz : z)
System.out.println(zz.getClass()+" " + zz.getName() + " " + zz.Noise() + " " + zz.getLegs());
System.out.println("press 0 to quit, anything else to change");
}
public void update(Zoo[] z) {
int legs = 0;
System.out.println("Change: 1.Dolphin 2. Chicken 3. Octopus ");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Dophin name: ");
z[0].setName(sc.next());
System.out.println("legs: ");
try {
legs = sc.nextInt();
if (legs != 0)
throw new ZooException("0 legs only");
else
z[0].setLegs(legs);
} catch (ZooException e) {
e.getMessage();
}
break;
case 2:
System.out.println(" Chicken name: ");
z[1].setName(sc.next());
System.out.println("legs: ");
try {
legs = sc.nextInt();
if (legs > 2 || legs < 0)
throw new ZooException("1-2 legs only");
else
z[1].setLegs(legs);
} catch (ZooException e) {
System.out.println(e.getMessage());
}
break;
case 3:
System.out.println(" Octopus name: ");
z[2].setName(sc.next());
System.out.println("legs: ");
try {
legs = sc.nextInt();
if (legs > 8 || legs < 0)
throw new ZooException("1-8 legs only");
else
z[2].setLegs(legs);
} catch (ZooException e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
public static void main(String[] args) {
testZoo t = new testZoo();
Zoo d = new Dolphin("Happy", 0);
Zoo c = new Chicken("Blue", 2);
Zoo o = new Octopus("Pants", 8);
Zoo[] z = new Zoo[] { d, c, o };
Scanner sc = new Scanner(System.in);
int ans = 1;
while (ans != 0) {
t.display(z);
ans = sc.nextInt();
if (ans==0)
break;
t.update(z);
}
}
}
- dvd mini manager
- array=Arrays.copyOf(array, newLen); //expand array
public class Dvdmgr {
DVD[] dvds= new DVD[3];
public Dvdmgr(){
dvds[0]= new DVD("Roman Holiday","out","2019-02-02",30);
dvds[1]= new DVD("Blue","in",1);
dvds[2]= new DVD("Animal House","in",12);
}
public void display(){
System.out.println("Count\tName");
for(DVD dvd: dvds){
System.out.println(dvd.getCount()+"\t"+dvd.getName());
System.out.println("************");
}
}
public void add(DVD dvd){
int oldLen=dvds.length;
int newLen= oldLen+1;
//replace old with new array
dvds=Arrays.copyOf(dvds, newLen);
dvds[newLen-1]=dvd;
}
public void menu(){
int ch=1;
do{
System.out.println("0. Movies Out List");
System.out.println("1. Add");
System.out.println("2. Exit");
System.out.println("Choose: ");
Scanner sc= new Scanner(System.in);
ch= sc.nextInt();
switch(ch){
case 0:
System.out.println("0. Movies Out List");
display();
break;
case 1:
System.out.println("1. Add");
System.out.println("Enter Name: ");
Scanner s= new Scanner(System.in);
String name= s.nextLine();
DVD dvd= new DVD(name,"in",1);
add(dvd);
System.out.println(name+" added!");
break;
case 2:
System.out.println("2. Exit");
System.out.println("THANKS!");
break;
default:
break;
}
}while(ch!=2);
}
}
class DVD{
private String name;
private String status;
private String borrowDate;
private int count;
public DVD() {}
public DVD(String name, String status, int count) {
super();
this.name = name;
this.status = status;
this.count=count;
}
public DVD(String name, String status, String borrowDate, int count) {
super();
this.name = name;
this.status = status;
this.borrowDate = borrowDate;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getBorrowDate() {
return borrowDate;
}
public void setBorrowDate(String borrowDate) {
this.borrowDate = borrowDate;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
class TestDVD{
public static void main(String[] args) {
Dvdmgr d=new Dvdmgr();
d.menu();
}
}