SlideShare a Scribd company logo
1 of 56
CS3101-3
Programming Language – Java
Fall 2013
Sept. 22
Road map today
Brief review
Details of class
Constructor
this reference
Inheritance
Overloading
Dynamic binding

Interface
Exceptions
What is Java
A programming language
A virtual machine – JVM
A runtime environment – JRE
Predefined libraries

Portable, but slow
Interpreter
JIT helps
Object and class
A class is a blueprint
An object is an instance created from that
blueprint
All objects of the same class have the
same set of attributes
Every Person object have name, weight, height

But different value for those attributes
ke.name=Ke Wang, sal.name=Sal Stolfo
Class Person: illustration
Name: Ke Wang
ke

height: 0
weight: 0

Name: Salvatore J. Stolfo
sal

height: 0
weight: 0
Reference
Person ke;

//only created the reference, not an object.
It points to nothing now (null).

ke = new Person();

ke.name=“Ke Wang”;

//create the object (allocate storage
in memory), and ke is initialized.

//access the object through
the reference

Can have multiple reference to one object
No reference means the object is inaccessible forever
– goes to garbage collector
Class Person: variables
Name: Ke Wang
ke

height: 0
weight: 0

x
Name: Salvatore J. Stolfo
sal

height: 0
weight: 0

references

objects
Visibility of fields and methods
Generally make fields private and provide
public getField() and setField() accessor
functions
O-O term: encapsulation
Private fields and methods cannot be
accessed from outside of the class.
Static vs. non-static
Static: class variable/method
Non-static: instance variable/method
Static ones are associated with class, not
object. Can be called using class name
directly
main() is static
Even though it’s in a class definition, no
instance of the class exist when main starts
executing
Static vs. non-static (cont.)
Instance fields define an object; the
values of those fields make one object
distinct from another
Instance method operates on an instance
of a class (object) instead of operating on
the class itself.
Class methods can only use class fields;
while instance methods can use both
instance fields and class fields
How instance method works?
Person a=new Person(), b=new Persion();
a.setWeight(100);

b.setWeight(120);

How can the method know whether it’s
been called for object a or b?
Internal: Person.setWeight(a, 100);

Invisible additional parameter to all
instance methods: this
It holds a reference to the object through
which the method is invoked
a.setWeight(100)  this=a
Keyword this
Can be used only inside method
When call a method within the same class, don’t
need to use this, compiler do it for you.
When to use it?
 method parameter or local variable in a method has
the same name as one of the fields of the class
 Used in the return statement when want to return the
reference to the current object.

Example …
Keyword this example I
class A{
int w;
public void setValue (int w) {
this.w = w; //same name!
}
}

When a method parameter or local variable in a
method has the same name as one of the fields
of the class, you must use this to refer to the field.
Keyword this example II
class Exp{
public int i=0;
public Exp increment () {
i++;
return this; // return current object
}
public static void main (String[] args){
Exp e = new Exp();
int v = e.increment().increment().i; // v=2!!
}
}
Object life cycle
Life cycles of dynamically created objects
C
 alloc() – use – free()

C++
 new() – constructor() – use – destructor()

Java
 new() – constructor() – use – [ignore / garbage
collection]
Constructor
A special method automatically called
when an object is created by new()
Java provide a default one that takes no
arguments and perform no special
initialization
Initialization is guaranteed
All fields set to default values: primitive types to
0 and false, reference to null
Constructor (cont.)
Must have the same name as the class
name
So the compiler know which method to call

Perform any necessary initialization
Format: public ClassName(para){…}
No return type, even no void!
It actually return current object

Notice: if you define any constructor, with
parameters or not, Java will not create the
default one for you.
Constructor example
class Circle{
double r;
public static void main(String[] args){
Circle c2 = new Circle(); // OK, default constructor
Circle c = new Circle(2.0); //error!!
}
}
Constructor example
class Circle{
double r;
public Circle (double r) {
this.r = r; //same name!
}
public static void main(String[] args){
Circle c = new Circle(2.0); //OK
Circle c2 = new Circle(); //error!!, no more default
}
}
Circle.java:8: cannot resolve symbol
symbol : constructor Circle ()
location: class Circle
Circle c2 = new Circle(); //error!!
^
1 error
Constructor example
class Circle{
double r;
public Circle(){
r = 1.0; //default radius value;
}
public Circle (double r) {
this.r = r; //same name!
}
public static void main(String[] args){
Circle c = new Circle(2.0); //OK
Circle c2 = new Circle(); // OK now!
}
}

Multiple constructor now!!
Method overload
It’s legal for a class to define more than one
method with the same name, as long as they
have different list of parameters
Different number of parameter, or different type of
parameter, or different order
Must be the same return type
The method can be static or not, or both: some are
static, some are not.

The compiler will decide which method to use
based on the number and type of arguments you
supply
Unsuccessful overloading
Return type is NOT enough!!
int foo (double d);
double foo (double d);

Won’t compile
What if in my code, I just have
foo(3.0);
Overload example
class Overload{
int r;
String s;
public void setValue (int r, String s) {
this.r = r;
this.s = s;
}
public void setValue (String s, int r) {
this.r =r;
this.s =s;
}
public static void main (String[] args){
Overload o = new Overload();
o.setValue(10, “ok”);
o.setValue(“ok?”, 20); //both are OK!
}
}

The compiler will decide which method to use based
on the number and type of arguments you supply
Rewrite:
class Overload{
int r;
String s;
public void setValue (int r, String s) {
this.r = r;
this.s = s;
}
public void setValue (String s, int r) {
this.setValue (r, s); //another usage of this
}
public static void main (String[] args){
Overload o = new Overload();
o.setValue(10, “ok”);
o.setValue(“ok?”, 20); //both are OK!
}
}

Avoid writing duplicate code
Multiple constructor
Can invoke one constructor from another
Use this(para)
Useful if constructors share a significant
amount of initialization code, avoid
repetition.
Notice: this() must be the first statement in
a constructor!! Can be called only once.
Example revisited
class Circle{
double r;
public Circle(){
// r = 1.0; //default radius value;
this (1.0); //call another constructor
}
public Circle (double r) {
this.r = r; //same name!
}
public static void main(String[] args){
Circle c = new Circle(2.0); //OK
Circle c2 = new Circle(); // OK now!
}
}
How to initialize static fields?
Cannot use constructor because no
object created
Static initializer:
static { code to do initialization}
Can appear anywhere in class definition where
a field definition can.
public static String days = new String[7];
static{
days[0]=“Monday”;
days[1]=“Tuesday”;
……
}
Finalization – opposite of initialization
Garbage collection can ONLY free the
memory resources
Need finalize() to free other resources, for
example, network connection, DB
connection, file handler, etc.
finalize() takes no argument, return void
Invoked automatically by Java
Rarely used for application-level
programming
Reusing classes
Suppose we want to define a class
Student, which has name, weight, height,
and school, gpa
We can redefine everything
Or, we can reuse the Person class since
Student is one kind of Person, and just
have additional attributes
Make Student inherit from Person
Avoid duplicate code
Inheritance
Extends definition of existing class
Keyword extends
Class Student extends Person{

Subclass Student inherit the fields and
methods from superclass Person
class Student extends Person{
String school;
double gpa;
}

Class Student automatically has fields name, weight,
height, and all the methods defined in class Person
Object class
If no superclass specified for a class, by default
the superclass is java.lang.Object
 All Java class inherit from Object
 Object is the only one without a superclass
Object

Person

Student

Math
System
Reader

InputStreamReader
FilterReader
StringReader

FileReader
Upcasting
The new class is a type of the existing class:
Student is type of Person
Any subclass object is also a legal superclass
object, no casting needed. But the reverse need
cast.
 Student s=new Student();
 Person p=s; //legal, auto upcasting
 s=(B)p; //need specific cast, and only if p is pointing to a
Student object

p=s is legal, but p cannot use any extra
fields/methods added by Student.
Example
class Hello{
public static void main(String[] args){
Student s = new Student();
Person p = s; //legal
p.school=“columbia”; //Error!
}
}
class Student extends Person{
String school;
double gpa;
}
Hello.java:12: cannot resolve symbol
symbol : variable school
location: class Person
p.school="lala";
^
1 error
Constructor chain
In subclass constructor, use super(param)
to invoke superclass constructor.
Super() similar to this()
Used only in constructor
Must be the first statement

By default, java implicitly call super() in
subclass constructor, form the constructor
chain.
Example
ChainCon.java
ChainCon

ChainCon2
ChainCon3
Shadowing superclass fields
In subclass, use same field name, but different
meaning
To refer to the field in superclass, use keyword
super, or type cast
Super can only refer to the direct parent, not
grandparent
A
super.x
((A)this).x

x

B
super.x
C

Each class has defined variable x, and
use the following inside C:
// x in C, same as this.x

super.x

// x in B, same as ((B)this).x

super.super.x // illegal, cannot point to A
((A)this).x // x in A
Override superclass method
Define method with same name, return type and
parameters in subclass
When the method is invoked for an object of this
class, the new definition of the method will be
called, not the superclass one.
 Runtime dynamic lookup to decide the type of object

Overloading vs overriding
 Overload: multiple definition for the same name
method in the same class
 Override: subclass re-define the same method from
superclass

Example: class A, B
Dynamic binding
Binding: connecting a method call o a
method body
Early binding (static binding): binding is
performed before the program is run
Dynamic binding: binding occurs at run
time, based on the type of the object
Java use this for all non-static methods

Some type information stored in the object
Example: shape, circle, square
final keyword
If a class declared with the final modifier,
then it cannot be extended or subclassed
If a field is declared with final, then the
value of it cannot be changed.
If a method is declared with final, then it
cannot be overridden in subclass
Access control modifier
Members of a class are always accessible within
the body of the class
public: accessible from outside of the class
private: only within this class, even not visible in
subclass
 Subclass inherit it, but cannot directly access it inside
the subclass

protected: accessible from itself and all the
subclasses
Abstract
Sometimes it’s helpful to have a common
superclass, without any real implementation :
abstract method
 abstract return-type methodname(); //No {}!!

A class with an abstract method must be
declared as abstract also.
 A class can be declared as abstract without having any
abstract method

An abstract class cannot be initiated
Static, private, final methods cannot be abstract
A subclass without implementing all the abstract
class still be abstract
Example
Revisit the Shape, Circle, Square code
abstract Shape

Circle

Square
Interface
A java class can extend only one
superclass, but can implement multiple
interface
Interface is like a class, but it’s a pure
abstract class
Define methods, but no implementation
Defines a public API. All methods are public.
No implementation, so nothing to hide

Cannot be instantiated, so no constructor
Implementing an interface
 Keyword: implements
 The class implementing the interface has to implement
all the methods, otherwise declare as abstract
Base class

Interface 1
Interface 2
Interface n

Base class methods

Interface 1 Interface 2

…

Interface n

class A extends Base implements i1, i2, i3 { … }
Each interface becomes an independent type that you can
upcast to.
Example
Adventure.java
C++ features not in Java
Multiple inheritance
interface kind of help on this one, since a class
can implement multiple interface

Template
Operator overload
Explosions
void method1() {…method2()}
void method2() {…method3()}
void method3() {…x=5/0} //BOOM!!

method3

method2
method1
Error handling
Java philosophy: “badly formed code will
not be run”
Ideal time to catch error: compile
Not all errors can be detected at compile
time; the rest must be handled at run time
Java: exception handling
The only official way that Java reports error
Enforced by compiler
Unexpected situation
User input errors
Device errors
Physics limits
Programmer errors
Exceptions are objects
throw new IOException();
throw new IOException(“file not open”);
Exception
IOException

……
SQLException

RuntimeException
……
IllegalArgumentException
……
NumberFormatException
Catching an exception
Guarded region
Try block
Exception handler
try{
//code that might generate exceptions
} catch (Type1 id1){
// handle exception for Type1
} catch (Type2 id2){
// handle exception for Type2
}

Only the first catch block with matching exception
type will be execute
Create your own exception
Create your own to denote a special
problem
Example: ExceptionTest.java
RuntimeException
Always thrown automatically by Java
You can only ignore RuntimeException in
coding, all other handling is carefully
enforced by compiler
RuntimeException represents programming
error
NullPointerException
ArrayIndexOutOfBoundsException
NumberFormatException
Finally clause – clean up
Always execute, regardless of whether the body
terminates normally or via exception
Provides a good place for required cleanup
 Generally involves releasing resources, for example,
close files or connections
try{
//code that might throw A or B exception
} catch (A a){
// handler for A
} catch (B b){
//handler for B
} finally {
//activities that happen every time, do cleanup
}
When to use Exception
90% of time: because the Java libraries
force you to
Other 10% of the time: your judgement
Software engineering rule of thumb
Your method has preconditions and
postcondition
If preconditions are met, but you can’t fulfill your
postconditions, throw an exception
Java tutorial for Beginners and Entry Level

More Related Content

What's hot (20)

Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Core java
Core java Core java
Core java
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
JAVA BASICS
JAVA BASICSJAVA BASICS
JAVA BASICS
 

Viewers also liked

Hadoop Installation Tutorial for KT ucloud biz
Hadoop Installation Tutorial for KT ucloud bizHadoop Installation Tutorial for KT ucloud biz
Hadoop Installation Tutorial for KT ucloud biz치완 박
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Sungchul Park
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)DK Lee
 
자바 네트워킹 기초에서 응용까지
자바 네트워킹 기초에서 응용까지자바 네트워킹 기초에서 응용까지
자바 네트워킹 기초에서 응용까지trustinlee
 
자바 웹 개발 시작하기 : 계획
자바 웹 개발 시작하기 : 계획자바 웹 개발 시작하기 : 계획
자바 웹 개발 시작하기 : 계획DK Lee
 
java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰Sungchul Park
 

Viewers also liked (6)

Hadoop Installation Tutorial for KT ucloud biz
Hadoop Installation Tutorial for KT ucloud bizHadoop Installation Tutorial for KT ucloud biz
Hadoop Installation Tutorial for KT ucloud biz
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
자바 네트워킹 기초에서 응용까지
자바 네트워킹 기초에서 응용까지자바 네트워킹 기초에서 응용까지
자바 네트워킹 기초에서 응용까지
 
자바 웹 개발 시작하기 : 계획
자바 웹 개발 시작하기 : 계획자바 웹 개발 시작하기 : 계획
자바 웹 개발 시작하기 : 계획
 
java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰
 

Similar to Java tutorial for Beginners and Entry Level

constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)ProCharm
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)quantumiq448
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 

Similar to Java tutorial for Beginners and Entry Level (20)

Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Java02
Java02Java02
Java02
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Chap11
Chap11Chap11
Chap11
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Lecture 2 classes i
Lecture 2 classes iLecture 2 classes i
Lecture 2 classes i
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 

More from Ramrao Desai

Enhanced Data rates for Global Evolution (EDGE)
Enhanced Data rates for Global Evolution (EDGE)Enhanced Data rates for Global Evolution (EDGE)
Enhanced Data rates for Global Evolution (EDGE)Ramrao Desai
 
Relational model for Databases
Relational model for DatabasesRelational model for Databases
Relational model for DatabasesRamrao Desai
 
Super Resolution in Digital Image processing
Super Resolution in Digital Image processingSuper Resolution in Digital Image processing
Super Resolution in Digital Image processingRamrao Desai
 
Using PowerPoint to Design Effective Presentations
Using PowerPoint to Design Effective PresentationsUsing PowerPoint to Design Effective Presentations
Using PowerPoint to Design Effective PresentationsRamrao Desai
 
Effective presentation for successful presentation
Effective presentation for successful presentationEffective presentation for successful presentation
Effective presentation for successful presentationRamrao Desai
 
Digital light processing
Digital light processingDigital light processing
Digital light processingRamrao Desai
 
Leading the way to an intelligent network
Leading the way to an intelligent networkLeading the way to an intelligent network
Leading the way to an intelligent networkRamrao Desai
 

More from Ramrao Desai (11)

Enhanced Data rates for Global Evolution (EDGE)
Enhanced Data rates for Global Evolution (EDGE)Enhanced Data rates for Global Evolution (EDGE)
Enhanced Data rates for Global Evolution (EDGE)
 
Relational model for Databases
Relational model for DatabasesRelational model for Databases
Relational model for Databases
 
Super Resolution in Digital Image processing
Super Resolution in Digital Image processingSuper Resolution in Digital Image processing
Super Resolution in Digital Image processing
 
Eerm mapping c++
Eerm mapping c++Eerm mapping c++
Eerm mapping c++
 
Using PowerPoint to Design Effective Presentations
Using PowerPoint to Design Effective PresentationsUsing PowerPoint to Design Effective Presentations
Using PowerPoint to Design Effective Presentations
 
Effective presentation for successful presentation
Effective presentation for successful presentationEffective presentation for successful presentation
Effective presentation for successful presentation
 
Internet Banking
Internet BankingInternet Banking
Internet Banking
 
Digital light processing
Digital light processingDigital light processing
Digital light processing
 
Capsule camera
Capsule cameraCapsule camera
Capsule camera
 
Cyber crime
Cyber crimeCyber crime
Cyber crime
 
Leading the way to an intelligent network
Leading the way to an intelligent networkLeading the way to an intelligent network
Leading the way to an intelligent network
 

Recently uploaded

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Recently uploaded (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Java tutorial for Beginners and Entry Level

  • 1. CS3101-3 Programming Language – Java Fall 2013 Sept. 22
  • 2. Road map today Brief review Details of class Constructor this reference Inheritance Overloading Dynamic binding Interface Exceptions
  • 3. What is Java A programming language A virtual machine – JVM A runtime environment – JRE Predefined libraries Portable, but slow Interpreter JIT helps
  • 4. Object and class A class is a blueprint An object is an instance created from that blueprint All objects of the same class have the same set of attributes Every Person object have name, weight, height But different value for those attributes ke.name=Ke Wang, sal.name=Sal Stolfo
  • 5. Class Person: illustration Name: Ke Wang ke height: 0 weight: 0 Name: Salvatore J. Stolfo sal height: 0 weight: 0
  • 6. Reference Person ke; //only created the reference, not an object. It points to nothing now (null). ke = new Person(); ke.name=“Ke Wang”; //create the object (allocate storage in memory), and ke is initialized. //access the object through the reference Can have multiple reference to one object No reference means the object is inaccessible forever – goes to garbage collector
  • 7. Class Person: variables Name: Ke Wang ke height: 0 weight: 0 x Name: Salvatore J. Stolfo sal height: 0 weight: 0 references objects
  • 8. Visibility of fields and methods Generally make fields private and provide public getField() and setField() accessor functions O-O term: encapsulation Private fields and methods cannot be accessed from outside of the class.
  • 9. Static vs. non-static Static: class variable/method Non-static: instance variable/method Static ones are associated with class, not object. Can be called using class name directly main() is static Even though it’s in a class definition, no instance of the class exist when main starts executing
  • 10. Static vs. non-static (cont.) Instance fields define an object; the values of those fields make one object distinct from another Instance method operates on an instance of a class (object) instead of operating on the class itself. Class methods can only use class fields; while instance methods can use both instance fields and class fields
  • 11. How instance method works? Person a=new Person(), b=new Persion(); a.setWeight(100); b.setWeight(120); How can the method know whether it’s been called for object a or b? Internal: Person.setWeight(a, 100); Invisible additional parameter to all instance methods: this It holds a reference to the object through which the method is invoked a.setWeight(100)  this=a
  • 12. Keyword this Can be used only inside method When call a method within the same class, don’t need to use this, compiler do it for you. When to use it?  method parameter or local variable in a method has the same name as one of the fields of the class  Used in the return statement when want to return the reference to the current object. Example …
  • 13. Keyword this example I class A{ int w; public void setValue (int w) { this.w = w; //same name! } } When a method parameter or local variable in a method has the same name as one of the fields of the class, you must use this to refer to the field.
  • 14. Keyword this example II class Exp{ public int i=0; public Exp increment () { i++; return this; // return current object } public static void main (String[] args){ Exp e = new Exp(); int v = e.increment().increment().i; // v=2!! } }
  • 15. Object life cycle Life cycles of dynamically created objects C  alloc() – use – free() C++  new() – constructor() – use – destructor() Java  new() – constructor() – use – [ignore / garbage collection]
  • 16. Constructor A special method automatically called when an object is created by new() Java provide a default one that takes no arguments and perform no special initialization Initialization is guaranteed All fields set to default values: primitive types to 0 and false, reference to null
  • 17. Constructor (cont.) Must have the same name as the class name So the compiler know which method to call Perform any necessary initialization Format: public ClassName(para){…} No return type, even no void! It actually return current object Notice: if you define any constructor, with parameters or not, Java will not create the default one for you.
  • 18. Constructor example class Circle{ double r; public static void main(String[] args){ Circle c2 = new Circle(); // OK, default constructor Circle c = new Circle(2.0); //error!! } }
  • 19. Constructor example class Circle{ double r; public Circle (double r) { this.r = r; //same name! } public static void main(String[] args){ Circle c = new Circle(2.0); //OK Circle c2 = new Circle(); //error!!, no more default } } Circle.java:8: cannot resolve symbol symbol : constructor Circle () location: class Circle Circle c2 = new Circle(); //error!! ^ 1 error
  • 20. Constructor example class Circle{ double r; public Circle(){ r = 1.0; //default radius value; } public Circle (double r) { this.r = r; //same name! } public static void main(String[] args){ Circle c = new Circle(2.0); //OK Circle c2 = new Circle(); // OK now! } } Multiple constructor now!!
  • 21. Method overload It’s legal for a class to define more than one method with the same name, as long as they have different list of parameters Different number of parameter, or different type of parameter, or different order Must be the same return type The method can be static or not, or both: some are static, some are not. The compiler will decide which method to use based on the number and type of arguments you supply
  • 22. Unsuccessful overloading Return type is NOT enough!! int foo (double d); double foo (double d); Won’t compile What if in my code, I just have foo(3.0);
  • 23. Overload example class Overload{ int r; String s; public void setValue (int r, String s) { this.r = r; this.s = s; } public void setValue (String s, int r) { this.r =r; this.s =s; } public static void main (String[] args){ Overload o = new Overload(); o.setValue(10, “ok”); o.setValue(“ok?”, 20); //both are OK! } } The compiler will decide which method to use based on the number and type of arguments you supply
  • 24. Rewrite: class Overload{ int r; String s; public void setValue (int r, String s) { this.r = r; this.s = s; } public void setValue (String s, int r) { this.setValue (r, s); //another usage of this } public static void main (String[] args){ Overload o = new Overload(); o.setValue(10, “ok”); o.setValue(“ok?”, 20); //both are OK! } } Avoid writing duplicate code
  • 25. Multiple constructor Can invoke one constructor from another Use this(para) Useful if constructors share a significant amount of initialization code, avoid repetition. Notice: this() must be the first statement in a constructor!! Can be called only once.
  • 26. Example revisited class Circle{ double r; public Circle(){ // r = 1.0; //default radius value; this (1.0); //call another constructor } public Circle (double r) { this.r = r; //same name! } public static void main(String[] args){ Circle c = new Circle(2.0); //OK Circle c2 = new Circle(); // OK now! } }
  • 27. How to initialize static fields? Cannot use constructor because no object created Static initializer: static { code to do initialization} Can appear anywhere in class definition where a field definition can. public static String days = new String[7]; static{ days[0]=“Monday”; days[1]=“Tuesday”; …… }
  • 28. Finalization – opposite of initialization Garbage collection can ONLY free the memory resources Need finalize() to free other resources, for example, network connection, DB connection, file handler, etc. finalize() takes no argument, return void Invoked automatically by Java Rarely used for application-level programming
  • 29. Reusing classes Suppose we want to define a class Student, which has name, weight, height, and school, gpa We can redefine everything Or, we can reuse the Person class since Student is one kind of Person, and just have additional attributes Make Student inherit from Person Avoid duplicate code
  • 30. Inheritance Extends definition of existing class Keyword extends Class Student extends Person{ Subclass Student inherit the fields and methods from superclass Person class Student extends Person{ String school; double gpa; } Class Student automatically has fields name, weight, height, and all the methods defined in class Person
  • 31. Object class If no superclass specified for a class, by default the superclass is java.lang.Object  All Java class inherit from Object  Object is the only one without a superclass Object Person Student Math System Reader InputStreamReader FilterReader StringReader FileReader
  • 32. Upcasting The new class is a type of the existing class: Student is type of Person Any subclass object is also a legal superclass object, no casting needed. But the reverse need cast.  Student s=new Student();  Person p=s; //legal, auto upcasting  s=(B)p; //need specific cast, and only if p is pointing to a Student object p=s is legal, but p cannot use any extra fields/methods added by Student.
  • 33. Example class Hello{ public static void main(String[] args){ Student s = new Student(); Person p = s; //legal p.school=“columbia”; //Error! } } class Student extends Person{ String school; double gpa; } Hello.java:12: cannot resolve symbol symbol : variable school location: class Person p.school="lala"; ^ 1 error
  • 34. Constructor chain In subclass constructor, use super(param) to invoke superclass constructor. Super() similar to this() Used only in constructor Must be the first statement By default, java implicitly call super() in subclass constructor, form the constructor chain.
  • 36. Shadowing superclass fields In subclass, use same field name, but different meaning To refer to the field in superclass, use keyword super, or type cast Super can only refer to the direct parent, not grandparent A super.x ((A)this).x x B super.x C Each class has defined variable x, and use the following inside C: // x in C, same as this.x super.x // x in B, same as ((B)this).x super.super.x // illegal, cannot point to A ((A)this).x // x in A
  • 37. Override superclass method Define method with same name, return type and parameters in subclass When the method is invoked for an object of this class, the new definition of the method will be called, not the superclass one.  Runtime dynamic lookup to decide the type of object Overloading vs overriding  Overload: multiple definition for the same name method in the same class  Override: subclass re-define the same method from superclass Example: class A, B
  • 38. Dynamic binding Binding: connecting a method call o a method body Early binding (static binding): binding is performed before the program is run Dynamic binding: binding occurs at run time, based on the type of the object Java use this for all non-static methods Some type information stored in the object Example: shape, circle, square
  • 39. final keyword If a class declared with the final modifier, then it cannot be extended or subclassed If a field is declared with final, then the value of it cannot be changed. If a method is declared with final, then it cannot be overridden in subclass
  • 40. Access control modifier Members of a class are always accessible within the body of the class public: accessible from outside of the class private: only within this class, even not visible in subclass  Subclass inherit it, but cannot directly access it inside the subclass protected: accessible from itself and all the subclasses
  • 41. Abstract Sometimes it’s helpful to have a common superclass, without any real implementation : abstract method  abstract return-type methodname(); //No {}!! A class with an abstract method must be declared as abstract also.  A class can be declared as abstract without having any abstract method An abstract class cannot be initiated Static, private, final methods cannot be abstract A subclass without implementing all the abstract class still be abstract
  • 42. Example Revisit the Shape, Circle, Square code abstract Shape Circle Square
  • 43. Interface A java class can extend only one superclass, but can implement multiple interface Interface is like a class, but it’s a pure abstract class Define methods, but no implementation Defines a public API. All methods are public. No implementation, so nothing to hide Cannot be instantiated, so no constructor
  • 44. Implementing an interface  Keyword: implements  The class implementing the interface has to implement all the methods, otherwise declare as abstract Base class Interface 1 Interface 2 Interface n Base class methods Interface 1 Interface 2 … Interface n class A extends Base implements i1, i2, i3 { … } Each interface becomes an independent type that you can upcast to.
  • 46. C++ features not in Java Multiple inheritance interface kind of help on this one, since a class can implement multiple interface Template Operator overload
  • 47. Explosions void method1() {…method2()} void method2() {…method3()} void method3() {…x=5/0} //BOOM!! method3 method2 method1
  • 48. Error handling Java philosophy: “badly formed code will not be run” Ideal time to catch error: compile Not all errors can be detected at compile time; the rest must be handled at run time Java: exception handling The only official way that Java reports error Enforced by compiler
  • 49. Unexpected situation User input errors Device errors Physics limits Programmer errors
  • 50. Exceptions are objects throw new IOException(); throw new IOException(“file not open”); Exception IOException …… SQLException RuntimeException …… IllegalArgumentException …… NumberFormatException
  • 51. Catching an exception Guarded region Try block Exception handler try{ //code that might generate exceptions } catch (Type1 id1){ // handle exception for Type1 } catch (Type2 id2){ // handle exception for Type2 } Only the first catch block with matching exception type will be execute
  • 52. Create your own exception Create your own to denote a special problem Example: ExceptionTest.java
  • 53. RuntimeException Always thrown automatically by Java You can only ignore RuntimeException in coding, all other handling is carefully enforced by compiler RuntimeException represents programming error NullPointerException ArrayIndexOutOfBoundsException NumberFormatException
  • 54. Finally clause – clean up Always execute, regardless of whether the body terminates normally or via exception Provides a good place for required cleanup  Generally involves releasing resources, for example, close files or connections try{ //code that might throw A or B exception } catch (A a){ // handler for A } catch (B b){ //handler for B } finally { //activities that happen every time, do cleanup }
  • 55. When to use Exception 90% of time: because the Java libraries force you to Other 10% of the time: your judgement Software engineering rule of thumb Your method has preconditions and postcondition If preconditions are met, but you can’t fulfill your postconditions, throw an exception