Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

JavaProgramming_Lecture02-6

Uploaded by

stacy russo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

JavaProgramming_Lecture02-6

Uploaded by

stacy russo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

AP/ITEC 2610 3.

00
Object Oriented
Programming
Lecture -2/3
Sept, 15th 2022 (4pm-7pm)
Sept, 22nd 2022 (4pm – 4:25pm)
Learning outcomes:
• Important Java facts
• Implement a class
• Implement a class with arguments
• Understand the purpose and use of constructors
• Encapsulation
• Understand how Java implements Classes in Byte Code – Next week
Java Facts
• Every Java application begins with a class name
• class name MUST match the file name
• Every line of code must be in a class
• A class name should start with a capital letter
• In Java functions are called methods
• Every Java application MUST have a main() method
• execution start in the main() method – Entry point
• methods MUST start with lower case
• JAVA is case sensitive
• In Java every line MUST terminate with a semi-colon (;)
Objects Class = Cell Nucleus Instance Variables Methods

•In Java, you build programs for


objects.
•Object is a software component to
mimic real world objects.
•Each object has certain
behaviors and properties.
• Dogs have property (name, Instance Variables
color, weight , breed, hungry)
and behavior (barking, fetching,
wagging tail).
• Cars also have states/property
(fuel consumption , color ,
current gear, current speed) and
behavior (changing gear,
accelerating, applying brakes ,
stopping , starting etc..).
Objects contd…
•Object: an entity in your program that you can manipulate by
calling one or more of its methods.
•Method: consists of a sequence of instructions that can access
the data of an object.
•Implemets the object’s behavior
•Provides interface between the variables and the outside world
• You do not know what the instructions are. You do know that the
behavior is well defined
• E.g., applying brakes on a car

• E.g., hissing, meowing and growling of a cat


Java Object Creation and
Destruction
• Java objects are created with the new method – Important!
• Java collects garbage automatically
• objects are deleted when they have no reference
• set an object to null to flag it for deletetion
• Any Java object can be created & destroyed
• simplest are basic data types, like strings and arrays – We will implement a
class called “String”
• Even simple objects Strings have methods associated with them
• the String class has a method called join
Note : Look up the term garbage collection
Classes
A class describes a set of objects with the same behavior
A class is like a blueprint for making objects.

• There may be thousands of other cars of the same make and


model.
• Each car was built from the same set of blueprints and therefore
contains the same components.
• In object-oriented terms, we say that a car is an instance of
the class of objects known as cars.
• A class is the blueprint from which individual objects are created.
Instance Variables
Instance variables store the data of an object.
- a storage location present in each object of the class.

The class declaration specifies the instance variables:


public class Counter
{
private int value;
...
}

An object's instance variables store the data required for executing


its methods.
Syntax:Instance Variable Declaration
Instance Variables :
Example
These clocks have common behavior, but each of them has a different state. Similarly, objects of a
class can have their instance variables set to different values.
A Java Construct
• A special type of subroutine in Java
• It is called to create an object
• It prepares the new object for use
• Even if you don’t create a construct of a class, Java will by default
create one called as ‘default constructor’
• Name of constructor should be same of the class name
• Can’t be declared as static or synchronize or abstract type
• Can’t have explicit return type (unlike methods)
• Can have an access modifier to control the access
Program extension: Adding an
argument to Hello World
program
• Write a Java program that asks a user to write two
strings of his choice at cmd line – Prints it out
• Join the two strings together – Prints it out
• If user forgets to provide an argument then we create
one ourselves for him - otherwise we would get an array
index error
/* Hello World with Args */
public class h {

public static void main(String[] args) {

// args is an array of strings -- first we need to know how many args we have

System.out.println("Hello Args: your number of args is"+" "+args.length);

// String is a class
// We can use the join method of the String class to join strings together
System.out.println(String.join(" ","joining","text","is","as simple as abc"));

// String join also works for arrays of strings


System.out.println("All args: "+String.join(" ",args));

// if user forgets to provide an arg then we create one ourselves for him
// otherwise we would get an array index error

if (args.length == 0) {args = new String[1]; args[0] = new String("You forgot your Arg");}
System.out.println(args[0]);

args = null; // we create objects with new and flag them for garbage collection by setting to
null
}
}
Operator Overloading
• Classes can define their own functions for operators
• operators are +, -. /, * etc
• Java String uses + for catenation of strings
• eg “Hello World: ” + args.length + “ items”
• this is called operator overloading
• Most object oriented languages allow classes to define their own
operators
• Java does not allow operator overloading
• … but they make an exception for String
• Why? Because the creator of Java, James Gosling thought people abused
operator overloading.
Creating your own Classes
• Classes are easy to define
• but they need to be in a different file
• Classes are constructed with a constructor
• constructors are just methods that have the same name as the
class
• constructors are optional, but Java secretly provides one for you if
you don’t
Class Example: Fractions

/* Hello World with Args */ /* The Fraction Class */


ublic class HelloFrac {
class Frac {
public static void main(String[] args) {
int n, d;
// args is an array of strings -- first we need to know how many args we have
System.out.println("Hello Args: your number of args is"+" "+args.length);
String name = ‘Programming in
// We can use the join method of the String class to join strings together
System.out.println(String.join(" ","joining","text","is","as simple as abc")); Java’;
// String join also works for arrays of strings }
System.out.println("All args: "+String.join(" ",args));

// if user forgets to provide an arg then we create one ourselves for him
// otherwise we would get an array index error
if (args.length == 0) {args = new String[1]; args[0] = new String("You forgot your Arg");}

System.out.println(args[0]);

Frac a = new Frac();


a.n = 1;
a.d = 3;
System.out.println("Type of Class: " + a.name);
System.out.println("Your Frac is: " + a.n + " over " + a.d);
args = null; // we create objects with new and flag them for garbage collection by setting to null

}
Constructing a Class
• Constructors are methods which run automatically when the object is
created
• they have the same name as the Class itself
• Constructors can be overloaded
• multiple methods with the same name but different arguments
Constructors of Class – Extending Frac class
/* Hello World with Args */ /* The Fraction Class */
ublic class HelloFrac { class Frac {
public static void main(String[] args) { int n, d;
String name = "Programming in Java";
// args is an array of strings -- first we need to know how many args we have
System.out.println("Hello Args: your number of args is"+" "+args.length);

// We can use the join method of the String class to join strings together
public Frac() {
System.out.println(String.join(" ","joining","text","is","as simple as abc")); n = 0;
// String join also works for arrays of strings
d=0;
System.out.println("All args: "+String.join(" ",args)); System.out.println("Empty Constructor
// if user forgets to provide an arg then we create one ourselves for him Called:");
// otherwise we would get an array index error }
if (args.length == 0) {args = new String[1]; args[0] = new String("You forgot your Arg");}
// Class Frac with an argument int i
System.out.println(args[0]); public Frac(int i) {
n = i;
Frac a = new Frac(); d = i;
Frac b = new Frac(3); System.out.println("Int Constructor Called: " + i);
System.out.println("Type of Class: " + a.name); }
System.out.println("Your Frac is: " + a.n + " over " + a.d); }

args = null; // we create objects with new and flag them for garbage collection by setting to null

}
Encapsulation
• Encapsulating means hiding sensitive data (mainly object’s
variables)from other objects in the program within a class from
external access.
• Meaning no code outside of the object can see or manipulate them.
• Hence, they can’t introduce bugs by accidentally modifying the
object’s state.
• In Java Classes components are either public or private
• Elements of a Java Class can be made private
• this means it can only be accessed from inside the class
Encapsulation
/* Hello World with Args */ /* The Fraction Class */
ublic class HelloFrac { class Frac {
public static void main(String[] args) { int n, d;
private String name = "To infinity and
// args is an array of strings -- first we need to know how many args we have
System.out.println("Hello Args: your number of args is"+" "+args.length);
beyond with Rational Numbers";

// We can use the join method of the String class to join strings together public String getName() { return name; }
System.out.println(String.join(" ","joining","text","is","as simple as abc"));

// String join also works for arrays of strings public Frac() {


System.out.println("All args: "+String.join(" ",args));
n = 0; d=0;
// if user forgets to provide an arg then we create one ourselves for him System.out.println("Empty
// otherwise we would get an array index error
if (args.length == 0) {args = new String[1]; args[0] = new String("You forgot your Arg");}
Constructor Called:");
}
System.out.println(args[0]);

public Frac(int i) {
Frac a = new Frac(); n = i; d=i;
Frac b = new Frac(3); System.out.println("Int Constructor
Called: " + i);
Frac c = new Frac(3,5); }
System.out.println("Type of Class: " + a.getName()); public Frac(int i, int j) {
System.out.println("Your Frac is: " + a.n + " over " + a.d); n = i; d=j;
System.out.println("Frac
args = null; // we create objects with new and flag them for garbage collection by setting to null
Constructor Called: " + i + " / " + j);
} }
}
Java Console I/O
• You can interact with a program directly through the Console
• the Console is also called the Command Line Interface (CLI) or Shell
• Consoles are text based interfaces
• Consoles display (print) text
• messages to the console are important for debugging
• Consoles also can read text from your keyboard
• input from the Arguments is the most basic
• input can also be read directly from the keyboard by the program
Java Console I/O Example Code:
/* Hello World with Console Input */
* Hello World with console */
ublic class HelloConsole {

public static void main(String[] args) {

System.console().printf("Enter some string of your choice: ");


String in = System.console().readLine();

if (args.length == 0) {args = new String[1]; args[0] = new String("Sorry, You forgot your Arg");}

System.console().writer().println(in);

}
JavaP - The javap tool is used to get the information of any class or
interface. The javap command (also known as the Java Disassembler) disassembles one or
more class files.

Command line Usage

Java Byte Code Version of


public class hello Main.java
(disassembled)
{
public static void main(java.lang.String[]);
public static void main(String[]
args) descriptor: ([Ljava/lang/String;)V
{ flags: (0x0009) ACC_PUBLIC, ACC_STATIC
System.out.println("Hello World"); Code:
} stack=2, locals=1, args_size=1
} 0: getstatic java/lang/System.out:Ljava/io/PrintStream;
3: ldc "Hello World"
5: invokevirtual
java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
Jasmin and Karatakau
• Jasmin is an assembler for the Java Virtual Machine.
• It takes ASCII descriptions of Java classes, written in a simple
assembler-like syntax using the Java Virtual Machine instruction set.
• It converts them into binary Java class files.
• The jasmin.jar file is an executable JAR file that runs Jasmin. For
example:
java -jar jasmin.jar myfile.j. or java Jasmin myfile.j
(Run to compile your .j file after installing Jasmine)
Source : http://jasmin.sourceforge.net/guide.html
Krakatau provides an assembler and disassembler for Java
bytecode, which allows you to convert binary class files to a
human readable text format.
krakatau syntax example for HelloWorld code jasmin syntax for HelloWorld code
.class public hello .class public hello
.super java/lang/Object .super java/lang/Object
.method public static main : ([Ljava/lang/String;)V .method public static main ([Ljava/lang/String;)V
.limit stack 10 ; up to ten items can be pushed .limit stack 2 ; up to two items can be pushed
.limit locals 10
getstatic java/lang/System out getstatic java/lang/System/out
Ljava/io/PrintStream; Ljava/io/PrintStream;
ldc "Helllo World!" ldc "Helo World!"
invokevirtual java/io/PrintStream println invokevirtual
(Ljava/lang/Object;)V java/io/PrintStream/println(Ljava/lang/String;)V
return
return
.end method
.end method
; code explained line-by-line
; code explained line-by-line
; ---------------------------
; ---------------------------
; push System.out onto the stack
; push System.out onto the stack
; push a string onto the stack
; push a string onto the stack
; call the PrintStream.println() method.
; call the PrintStream.println() method.

Do it yourself drill
Homework:
Online reading
• Java OOP (Object-Oriented Programming)
https://www.w3schools.com/java/java_oop.asp
• Java Classes and Objects
https://www.w3schools.com/java/java_classes.asp
• Java Class Methods
https://www.w3schools.com/java/java_class_methods.asp
• Java Constructors
https://www.w3schools.com/java/java_constructors.asp
• Java Encapsulation and Getters and Setters
https://www.w3schools.com/java/java_encapsulation.asp

You might also like