Overview of OOP in Java Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - 3131 1
Outline • Java Basics • Classes and Objects • Encapsulation • Inheritance • Polymorphism 2
Java Program Structure • Java is a pure object oriented language • Everything is written within a class block. [Documentation] [package statement] [import statement(s)] [interface statement(s)] [class definition(s)] main method class definition 3
Java Program Structure // this is a java program import java.lang.*; class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } 4
Java Program Structure • Java program = Comments + Token(s) + white space • Comments – Java supports three types of comment delimiters – The /* and */ - enclose text that is to be treated as a comment by the compiler – // - indicate that the rest of the line is to be treated as a comment by the Java compiler – the /** and */ - the text is also part of the automatic class documentation that can be generated using JavaDoc. 5
Java Program Structure • Five types of Tokens in Java: – Reserved keywords – Identifiers – Literals – Operators – Separators 6
Reserved keywords • Words with special meaning to the compiler • The following keywords are reserved in the Java language. They can never be used as identifiers: abstract assert boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void violate while • Some are not used but are reserved for further use. (Eg.: const, goto) 7
Identifiers • Programmer given names • Identify classes, methods, variables, objects, packages. • Identifier Rules: – Must begin with • Letters , Underscore characters ( _ ) or Any currency symbol – Remaining characters • Letters • Digits – As long as you like!! (until you are tired of typing) – The first letter can not be a digit – Java is case sensitive language 8
Identifiers • Identifiers‘ naming conventions – Class names : starts with cap letter and should be inter-cap e.g. StudentGrade – Variable names : start with lower case and should be inter- cap e.g. varTable – Method names : start with lower case and should be inter- cap e.g. calTotal – Constants : often written in all capital and use underscore if you are using more than one word. 9
Literals • Explicit (constant) value that is used by a program • Literals can be digits, letters or others that represent constant value to be stored in variables – Assigned to variables – Used in expressions – Passed to methods • E.g. – Pi = 3.14; // Assigned to variables – C= a * 60; // Used in expressions – Math.sqrt(9.0); // Passed to methods 10
Operator • symbols that take one or more arguments (operands) and operates on them to produce a result • 5 Operators – Arithmetic operators – Assignment operator – Increment/Decrement operators – Relational operators – Logical operators 11
Separators • Indicate where groups of codes are divided and arranged Name Symbol Parenthesis () braces {} brackets [] semicolon ; comma , , . period 12
Object Oriented Programming • Objects and Classes • Encapsulation • Inheritance • Polymorphism 13
Classes and Objects • The underlying structure of all Java programs is classes. • Anything we wish to represent in Java must be encapsulated in a class – defines the ―state‖ and ―behavior‖ of the basic program components known as objects. • Classes create objects • A class essentially serves as a template for an object and behaves like a basic data type ― int ‖ . 14
Classes and Objects • A class is a collection of fields (data) and methods (procedure or function) that operate on that data. • The basic syntax for a class definition : class ClassName { [fields declaration] [methods declaration] } 15
Classes and Objects Rectangle Length Width Perimeter() area() public class Rectangle{ // my rectangle class } 16
Adding Fields • The fields and methods are called class members • Add fields: public classRectangle { public double length; public double width; } • The fields (data) are also called the instance variables. 17
Adding Methods • A class with only data fields has no life. Objects created by such a class cannot respond to any messages. • Methods are declared inside the body of the class but immediately after the declaration of data fields. • The general form of a method declaration is: type MethodName (parameter-list) { Method-body; } 18
Adding Methods public class Rectangle { public double length public double width; // //Methods to return perimeter and area public double perimeter() { return 2 *(length+width); } public double area() { Method Body return length * width; } } 19
Creating an Object • An object is an instance of a class • Uniquely identified by – its name – defined state, • represented by the values of its attributes in a particular time 20
Creating an Object • Creating an object is a two step process – Creating a reference variable Syntax: – <class idn><ref. idn>; eg. Rectangle r1 ; – Setting or assigning the reference with the newly created object. – Syntax: <ref. idn> = new <class idn>( … ); r1 = new Rectangle(); – The two steps can be done in a single statement Rectangle r1 = new Rectangle(); 21
Creating an Object • Example – Rectangle aRec,bRec ; • aRec, bRec simply refers to a Rectangle object, not an object itself. aRec bRec null null 22
Creating an Object • Objects are created dynamically using the new keyword. aRec= new Rectangle() ; bRec= new Rectangle() ; • aRec and bRec refer to Rectangle objects 23
Creating an Object aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; Before Assignment After Assignment aCircle bCircle aCircle bCircle 24
Accessing Object Data • We use dot (“.”) operator ObjectName.VariableName ObjectName.MethodName(parameter-list) Rectangle aRec= new Rectangle(); aRec.length = 2.0 // initialize length aRec.width = 2.0 //initialize width 25
Executing Methods in Object/Circle • Using Object Methods: sent ‘message’ to aRec Rectangle aRec= new Rectangle(); double area; aCircle.r= 1.0; area = aRec.area(); 26
Using Rectangle Class //Add Rectangle class code here class MyMain { public static void main(String args[]) { Rectangle aRec; // creating reference aRec= new Rectangle(); aRec.length = 2.0 // initialize length aRec.width = 2.0 //initialize width double area = aRec.area(); // invoking method double per = aRec.perimeter(); System.out.println (“Area is “+area); System.out.println (“Perimeter is “+ per); } } 27
What is encapsulation? • Hiding the data within the class • Making it available only through the methods • Each object protects and manages its own data. This is called self-governing . Methods Data 28
Why encapsulation? • To hide the internal implementation details of your class so they can be easily changed • To protect your class against accidental or willful mistakes • In general – Encapsulation separates the implementation details from the interface 29
Visibility Modifiers • In Java we accomplish encapsulation using visibility modifiers. – Public • least restrictive • Can be directly referenced from outside of an object. • visible to any class in the Java program – Private • most restrictive • Can’t be accessed by anywhere outside the enclosing class • Cannot be referenced externally. • Instance data should be defined private. – Package - default • Intermediate b/n private and public • access only to classes in the same package – Protected • access to classes in the same package and to all subclasses 30
Using Set and Get Methods • A class‘s private fields can manipulate only by methods of that class • How can we access those data outside? – Using set and get methods • Set methods – public method that sets private variables – Does not violate notion of private data • Change only the variables you want – Called mutator methods (change value) • Get methods – public method that displays private variables – Again, does not violate notion of private data • Only display information you want to display – Called accessor or query methods 31
Inheritance • Inheritance allows a software developer to derive a new class from an existing one • For the purpose of – reuse – enhancement, – adaptation, etc • The existing class is called the parent class or superclass • The derived class is called the child class or subclass . • Classes often have a lot of state and behavior in common – Result: lots of duplicate code! • Super classes are more generic and sub classes are specific version of the super classes 32
Recommend
More recommend