Download presentation
Presentation is loading. Please wait.
Published byGladys Blair Modified over 7 years ago
1
Java Tutorial Mr.Arun Kumar.P, Asst.Proff.,ISE Dept., JNNCE, Shimoga
4th Sem ISE, B Sectionp 8th March and 7th April 2017p 1
2
Object-Oriented Programming
3
Different Programming Paradigms
Functional/procedural programming: program is a list of instructions to the computer Object-oriented programming program is composed of a collection objects that communicate with each other flexibility, easing changes to programs easier to learn simpler to develop, maintain and analysize
4
Main Concepts Object Class Inheritance Encapsulation
5
Objects identity – unique identification of an object
attributes – data/state services – methods/operations supported by the object within objects responsibility to provide these services to other clients
6
Class “type” object is an instance of class
class groups similar objects same (structure of) attributes same services object holds values of its class’s attributes
7
class <ClassName>
{ attributes/variables; Constructors(); methods(); }
8
Instance is an Object of a class which is an entity with its own attribute values and methods.
Creating an Instance ClassName refVariable; refVariable = new Constructor(); or ClassName refVariable = new Constructor();
9
Encapsulation Separation between internal state of the object and its external aspects How ? control access to members of the class interface “type”
10
Java Java is an object-oriented language, with a syntax similar to C
Structured around objects and methods A method is an action or something you do with the object Avoid those overly complicated features of C++: Operator overloading, pointer, templates, friend class, etc.
11
Why Java ? Portable Easy to learn
[ Designed to be used on the Internet ]
12
Intro to Java Java programming language Java virtual machine (JVM)
The one we use to write our program Compiled to byte code of JVM Java virtual machine (JVM) Java interpreter – interpret the compiled byte code Software simulated CPU architecture Cross-platform: support Linux, Windows, PalmOS…etc. Java runtime environment (JRE) Predefined set of java classes available to use Core Java APIs – basic utilities, I/O, graphics, network…
13
JVM JVM stands for Java Virtual Machine
Unlike other languages, Java “executables” are executed on a CPU that does not exist.
14
Platform Dependent gcc machine code OS/Hardware Platform Independent
myprog.exe myprog.c machine code C source code OS/Hardware JVM bytecode Java source code myprog.java javac myprog.class OS/Hardware Platform Independent
15
Bottom line: slow but safe
Not suitable for high-performance computation Scientific computation, games, OS kernel Compiled to byte codes of JVM, not native machine language instructions New release of Java is improving the speed a lot Just-in-time (JIT) compiler: convert byte codes to native machine language on the fly Very safe No pointer Automatic garbage collection Check array access bound
16
Hello World! File name: Hello.java
/* Our first Java program – Hello.java */ public class Hello { //main() public static void main ( String[] args ) { System.out.println( "hello world!" ); } Command line arguments Standard output, print with new line
17
Hello World Hello.java ( compilation creates Hello.class )
class Hello { public static void main(String[] args) { System.out.println(“Hello World !!!”); } } C:\javac Hello.java C:\java Hello ( compilation creates Hello.class ) (Execution on the local JVM)
18
About class Fundamental unit of Java program
All java programs are classes Each class define a unique kind of object ( a new data type) Each class defines a set of fields, methods or other classes public: modifier. This class is publicly available and anyone can use it.
19
What is class? Class introduces a new data type
A class describes a set of objects that have identical characteristics (data elements) and behaviors (methods). Existing classes provided by JRE User defined classes Once a class is established, you can make as many objects of it as you like, or none.
20
Data Abstraction Data Abstractions organize data. StudentType
Name (string) Marks (num) Grade (char) Student Number (num)
21
Behavioral Abstraction
Behavioral Abstractions combine procedural and data abstractions. Data State Enqueue Is Full Is Empty Dequeue Initialize Queue Object
22
Simple example: class Person
A Person has some attributes The class defines these properties for all people Each person gets his own copy of the fields Attributes = properties = fields
23
Class Person: definition
String name; int height; //in inches int weight; //in pounds public void printInfo(){ System.out.println(name+" with height="+height+", weight="+weight); } class ClassName{ /* class body goes here */ } class: keyword
24
Class Person: usage Person ke; //declaration
ke = new Person(); //create an object of Person ke.name= “Ke Wang”; //access its field Person sal = new Person(); sal.name=“Salvatore J. Stolfo”; ke.printInfo(); Sal.printInfo(); // error here??
25
Class Person Name: Ke Wang height: 0 weight: 0 ke
Name: Salvatore J. Stolfo height: 0 weight: 0 sal
26
Things to notice Java is case sensitive
whitespace doesn’t matter for compilation File name must be the same as one of the class names, including capitalization! At most one public class per file If there is one public class in the file, the filename must be the same as it Generally one class per file
27
Things to notice Java is case sensitive
whitespace doesn’t matter for compilation File name must be the same as one of the class names, including capitalization! At most one public class per file If there is one public class in the file, the filename must be the same as it Generally one class per file
28
What is an object? Object is a thing
An object has state, behavior and identity Internal variable: store state Method: produce behavior Unique address in memory: identity An object is a Instance of a class
29
More sophisticated Default C’tor Copy C’tor class Kyle {
private boolean kennyIsAlive_; public Kyle() { kennyIsAlive_ = true; } public Kyle(Kyle aKyle) { kennyIsAlive_ = aKyle.kennyIsAlive_; } public String theyKilledKenny() { if (kennyIsAlive_) { kennyIsAlive_ = false; return “You bastards !!!”; } else { return “?”; public static void main(String[] args) { Kyle k = new Kyle(); String s = k.theyKilledKenny(); System.out.println(“Kyle: “ + s); Default C’tor Copy C’tor
30
More sophisticated Default C’tor Copy C’tor class Kyle {
private boolean kennyIsAlive_; public Kyle() { kennyIsAlive_ = true; } public Kyle(Kyle aKyle) { kennyIsAlive_ = aKyle.kennyIsAlive_; } public String theyKilledKenny() { if (kennyIsAlive_) { kennyIsAlive_ = false; return “You bastards !!!”; } else { return “?”; public static void main(String[] args) { Kyle k = new Kyle(); String s = k.theyKilledKenny(); System.out.println(“Kyle: “ + s); Default C’tor Copy C’tor
31
Results javac Kyle.java ( to compile ) java Kyle ( to execute )
Kyle: You bastards !!!
32
Access Control public member (function/data) protected private
Can be called/modified from outside. protected Can be called/modified from derived classes private Can be called/modified only from the current class default ( if no access modifier stated ) Usually referred to as “Friendly”. Can be called/modified/instantiated from the same package.
33
Methods allows to reuse a sequence of statements
Inheritance allows to reuse classes by deriving a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass. The child class inherits characteristics of the parent class(i.e the child class inherits the methods and data defined for the parent class 33
34
Inheritance Generalization and Specialization (Cntd...)
- subclass inherits attributes and services from its superclass - subclass may add new attributes and services - subclass may reuse the code in the superclass - subclasses provide specialized behaviors (overriding and dynamic binding) - partially define and implement common behaviors (abstract)
35
Inheritance (Cntd...) Base Derived
class Base { Base(){} Base(int i) {} protected void foo() {…} } class Derived extends Base { Derived() {} Derived(int i) { super(i); … super.foo(); (Cntd...) Base Derived As opposed to C++, it is possible to inherit only from ONE class. Pros avoids many potential problems and bugs. Cons might cause code replication
36
Inheritance In Java, all methods are virtual : (Cntd...) class Base {
void foo() { System.out.println(“Base”); } class Derived extends Base { System.out.println(“Derived”); public class Test { public static void main(String[] args) { Base b = new Derived(); b.foo(); // Derived.foo() will be activated
37
Polymorphism Inheritance creates an “is a” relation:
(Cntd...) Inheritance creates an “is a” relation: For example, if B inherits from A, than we say that “B is also an A”. Implications are: access rights (Java forbids reducing access rights) - derived class can receive all the messages that the base class can. behavior precondition and postcondition
38
Inheritance (3) - Optional
(Cntd...) class classC extends classB { classC(int arg1, int arg2){ this(arg1); System.out.println("In classC(int arg1, int arg2)"); } classC(int arg1){ super(arg1); System.out.println("In classC(int arg1)"); class classB extends classA { classB(int arg1){ System.out.println("In classB(int arg1)"); classB(){ System.out.println("In classB()");
39
Inheritance (3) - Optional
(Cntd...) class classA { classA(int arg1){ System.out.println("In classA(int arg1)"); } classA(){ System.out.println("In classA()"); class classB extends classA { classB(int arg1, int arg2){ this(arg1); System.out.println("In classB(int arg1, int arg2)"); classB(int arg1){ super(arg1); System.out.println("In classB(int arg1)"); } class B() { System.out.println("In classB()"); }
40
(Cntd...) Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Animal weight : int + getWeight() : int Bird + fly() : void 40
41
In Java, class “Object” is the base class to all other classes
(Cntd...) In Java, class “Object” is the base class to all other classes If we do not explicitly say extends in a new class definition, it implicitly extends Object The tree of classes that extend from Object and all of its subclasses are is called the class hierarchy All classes eventually lead back up to Object This will enable consistent access of objects of different classes.
42
Abstract abstract member function, means that the function does not have an implementation. abstract class, is class that can not be instantiated. AbstractTest.java:6: class AbstractTest is an abstract class. It can't be instantiated. new AbstractTest(); ^ 1 error NOTE: An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it or that does not provide an implementation for any abstract methods declared in its superclasses must be declared as an abstract class. Example
43
Abstract - Example package java.lang; public abstract class Shape {
public abstract void draw(); public void move(int x, int y) { setColor(BackGroundColor); draw(); setCenter(x,y); setColor(ForeGroundColor); } package java.lang; public class Circle extends Shape { public void draw() { // draw the circle ... }
44
Interface Interfaces are useful for the following:
Capturing similarities among unrelated classes without artificially forcing a class relationship. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class.
45
Interface Example abstract “class”
Helps defining a “usage contract” between classes All methods are public Java’s compensation for removing the multiple inheritance. You can “inherit” as many interfaces as you want. Example * - The correct term is “to implement” an interface
46
Interface interface IChef { void cook(Food food); }
interface BabyKicker { void kickTheBaby(Baby); } interface SouthParkCharacter { void curse(); } class Chef implements IChef, SouthParkCharacter { // overridden methods MUST be public // can you tell why ? public void curse() { … } public void cook(Food f) { … } } * access rights (Java forbids reducing of access rights)
47
When to use an interface ?
Perfect tool for encapsulating the classes inner structure. Only the interface will be exposed
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.