Download presentation
Presentation is loading. Please wait.
Published byNelson Garrison Modified over 6 years ago
1
Object-Orientated Analysis, Design and Programming
Presentation by Dr. Phil Legg Senior Lecturer Computer Science 4: Java Programming Autumn 2016
2
Session Aims To understand relevant terminologies
To know the basic syntax of a Java program and methods To know how to group classes into packages To know how to use the Scanner class To know how to create, compile and run Java programs using NetBeans
3
HelloWorld.java public class HelloWorld {
public static void main(String[] args) { System.out.println("Hello World"); }
4
Recommended: Atom, Sublime Text, TextPad
Command Line Tools To compile a source code file: javac HelloWorld.java To run a compiled program: java HelloWorld Text Editors Recommended: Atom, Sublime Text, TextPad
5
Recommended: NetBeans, IntelliJ, Eclipse
Integrated Developer Environment (IDE) IDEs have much more support for developers, e.g. Built-in compiler / debugger Code syntax highlighting Code completion IDEs Recommended: NetBeans, IntelliJ, Eclipse
6
In-Class Activity Install the Java Developer Kit (JDK)
Compile and Run 'HelloWorld' using the command line tools Setup a 'HelloWorld' project using an IDE of your choice, and compile and run the program
7
Online Java Resources Oracle Java Tutorials
Oracle Learning the Language New features are often introduced with new releases - Oracle's APIs and tutorials are well-maintained to be up-to-date.
8
Basic concepts of Java Classes and Packages Scanner Methods
Loops and Switches Arrays and Lists
9
Classes and Packages Everything in Java is part of a Class
Packages are used to group Classes Package can contain other packages
10
Packaging HelloWorld package learningjava; public class HelloWorld {
”learningjava” is a directory that contains all class files Can execute using: java learningjava.HelloWorld package learningjava; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); }
11
Using Classes from other Packages
Use the fully qualified name of the class: Use the import statement: Import all classes from a package: The import statement tells the compiler where to locate the classes java.util.Scanner import java.util.Scanner; import java.util.*;
12
Reading Input from the User
package learningjava; import java.util.Scanner; public class ReadInput { public static void main(String[] args) { String name = ""; Scanner scan = new Scanner( System.in ); System.out.println( "Enter your name:" ); name = scan.nextLine(); System.out.println( "Hello " + name ); }
13
Using Methods in Java public class Welcome {
public static void main( String[] args ) { prompt(); String name = getName(); System.out.println( name ); } public static void prompt() { System.out.println( "Enter your name" ); public static String getName() { Scanner in = new Scanner( System.in ); String nm = in.nextLine(); return nm;
14
Using Classes in Java public class Circle { double radius = 1.0;
} Circle(double newRadius) { radius = newRadius; } double findArea() { return radius * radius * ;
15
Defining Methods in Java
The format of a method is return_type can be void if the method does not return any value List of parameters can be empty if the method does not take any parameter: The import statement tells the compiler where to locate the classes return_type method_name(parameters) void setRadius(double newR){ radius = newR; } double findArea()
16
Constructors Circle() and Circle(doubleRadius) are called the constructors. A constructor of a class is invoked when an object of that class is created. It plays the role of initializing objects. A class may have more than one constructor, more than one way to create an instance. Constructors must have the same name as the class itself. A constructor with no parameters is referred to as a no-arg constructor, e.g. Circle()
17
Creating new objects To create new objects, we can simply use the new operator. Variables can now be accessed using the named reference: // Create a circle with default radius Circle firstCircle = new Circle(); // Create a circle with radius specified Circle secondCircle = new Circle(2.5); firstCircle.radius; secondCircle.findArea();
18
Visibility modifiers public: The data or method is visible to any class in any package. private: The data or methods can be accessed only by the declaring class. By default, the data or method can be accessed by any class in the same package.
19
Visibility modifiers package p1; public class FirstClass {
public int x; int y; private int z; public void m1() { } void m2() { } private void m3() { } } public class SecondClass { FirstClass fc = new FirstClass(); // can access fc.x and fc.y // can not access fc.z // can invoke fc.m1() and fc.m2() // can not invoke fc.m3() package p2; public class ThirdClass { FirstClass fc = new FirstClass(); // can access fc.x // can not access fc.y // can not access fc.z // can invoke fc.m1() // can not invoke fc.m2() // can not invoke fc.m3() }
20
Accessors and Modifiers
Following the principle that data should be encapsulated, data fields should be declared private. However, private attributes are not accessible from outside its object. To allow other objects access, or modify a private data field in a controlled way, we provide public get method and set methods to manipulate private data. public double getRadius(){ return radius; } public void setRadius( double newR ) { if ( newR < 1 ) radius = 1; else radius = newR;
21
Passing object references as parameters
public boolean equalSize(Circle o) { return radius == o.getRadius(); } public static void main(String[] args) { Circle c1= new Circle(2.0); Circle c2 = new Circle(1.5); System.out.println("C1 and C2 are of the same size: ” + c1.equalSize(c2));
22
Returning object reference from a method
public Circle biggerCircle() { double newR = radius * 2; return ( new Circle( newR ) ); } public static void main( String[] args ) { Circle c1 = new Circle( 2.0 ); Circle c2 = c1.biggerCircle(); double r = c2.getRadius();
23
Working with Arrays // To declare an arrays of objects
Circle[] circleArray = new Circle[10]; // To create 10 circle objects: for (int i = 0; i < 10; i++) { circleArray[i] = new Circle( 10 + i ); } public void printCircleArray() { System.out.println( "Radius\t\t" + "Area" ); System.out.println( circlearray[i].getRadius() + "\t" + circlearray[i].findArea() );
24
ArrayLists vs Arrays Limitations with array is that its size is fixed once the array is created Java provides the ArrayList class in which the size of the array is not fixed void add(Object o) appends o at the end of the list void add(int index, Object o) adds o at the specified index in the list boolean contains(Object o) returns true if o is in the list Object get(int i) returns the element at position i in the list boolean isEmpty() returns true if the list is empty boolean remove(Object o) removes element from the list boolean remove(int i) removes the element at position i int size() returns the number of elements in the list
25
Working with ArrayLists
public class ArrayListCircles() { ArrayList circlelist = new ArrayList(); public ArrayListCircles() { for (int i = 0 ; i < 10 ; i++) { circlelist.add(i, new Circle(i)); } public void printCircleList() { System.out.println( "Radius\t\t" + "Area" ); for (Circle c: circlelist){ System.out.println( c.getRadius() + "\t" + c.findArea() );
26
Static methods and variables
Variables such as radius in the Circle example are called instance variables. They belong to each instance A static variable is shared among all instances of a class. Only one copy of a static variable for all objects of the class. Static variables are also called class variables Similarly, there is the concept of static methods We do not have to instantiate an object of a class in order to invoke a static method. Static methods are invoked through the class name.
27
Method Overloading Allows us to define two or more methods that have the same method name but take different parameters You cannot overload methods based on different return type Can make programs clearer and more readable. Methods that perform closely related tasks should be given the same name. public class MethodOverloading { int maxNum( int i, int j ){ if ( i > j ) return i; else return j; } int maxNum( int i, int j, int k ){ int tmp = maxNum(i,j); return maxNum( tmp,k ); MethodOverloading test = new MethodOverloading(); int someTestValue = test.maxNum(5,3); int anotherTestValue = test.maxNum(5,3,6);
28
Exception Handling What should happen if an error occurs?
division by zero array index out of bounds file does not exist null pointer I/O exception Exceptions allow you to manage for when an error may be possible. class SomeExceptions { public int divide( int m ) { Scanner in=new Scanner(System.in); int n = in.nextInt(); // get the value of the divisor return m/n; } public class IllustrateException { public static void main(String [] args) { SomeExceptions myProg = new SomeExceptions(); System.out.println(myProg.divide(100));
29
Exception Handling (2) class SomeExceptions { int maxInt = 999999999;
public int divide( int m ){ Scanner in = new Scanner( System.in ); int n = in.nextInt(); try { return m / n; } catch ( ArithmeticException e ) { System.out.println( "An exception has occurred." ); System.out.println( "A big number is returned as a default." ); return maxInt; }
30
Exception Handling (3) public class IllustrateException {
public static void main(String[] args) { SomeExceptions myProg = new SomeExceptions(); try { System.out.println(myProg.divide(100)); } catch (ArithmeticException e){ System.out.println("exception happened, caught at outer level."); }
31
Loops and Switches for (int i=0; i < n; i++) { int month = 2;
// repeat this n times // i increases by 1 each time; // i=0, i=1, ..., i=n-1 } int month = 2; String monthString; switch (month) { case 1: monthString=“Jan”; break; case 2: monthString=“Feb”; case 3: monthString=“Mar”; ... default: monthString=“Error”; }
32
Arrays How do Arrays and ArrayLists differ? int[] anArray;
// here length is stated anArray = new int[10]; anArray[0] = 100; anArray[1] = 20; anArray[2] = 80; // or // here length is implied int[] anArray = {100,20,80,40,60,50,10,20};
33
Lists ArrayList list = new ArrayList(); list.add(“first”);
list.add(“second”); list.add(7); Iterator it = list.iterator(); while( it.hasNext() ) { System.out.println( it.next() ); }
34
Summary Introduced the Java programming language
Learnt how to use command line tools and IDE tools Learnt how to use Classes and Packages Learnt how to take input from a user using the Scanner class Learnt about Arrays, Lists, Loops and Switches for developing logic
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.