890 likes | 1.09k Views
OOP with Java. Course objectives. OOP Introduction Principles of OOP Java OOP. Learning Approach. The following are strongly suggested for a better learning and understanding of this course: Noting down the key concepts in the class Analyze all the examples / code snippets provided
E N D
Course objectives • OOP Introduction • Principles of OOP • Java OOP
Learning Approach • The following are strongly suggested for a better learning and understanding of this course: • Noting down the key concepts in the class • Analyze all the examples / code snippets provided • Study and understand the self study topics • Completion and submission of all the assignments, on time • Completion of the self review questions in the lab guide • Study and understand all the artifacts including the reference materials / e-learning / supplementary materials specified • Completion of the project (if application for this course) on time inclusive of individual and group activities • Taking part in the self assessment activities • Participation in the doubt clearing sessions
Procedural Programming • Back in the "old days" we had Procedural Programming: • Data was separate from code. • Programmer is responsible for organizing everything in to logical units of code/data. • No help from the compiler/language for enforcing modularity, … It’s hard to build large systems (not impossible, just hard).
What is OOP • It stands for Object Oriented Programming. • OOPis a design philosophy. • OOP is a programming paradigm. • It using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs
Why OOP? • The objects are the most stable factor in the problem • Algorithms may be improved • Implementations may be modified • Interface may undergo major changes • If the data structure for the objects is defined according to algorithm / implementation / interface it is very likely to backfire when one of them is changed. • Objects are the appropriate level at which decisions about encapsulation (information hiding) are made.
Why OOP? • OOP systems can be easily upgraded from small to large scale. • It is easy to partition the work in a project based on objects. • It reduces software maintenance and developing costs. • Changes in user requirements or later developments have always been a major problem. OOP can be the ultimate solution in this case. • OOP should help in developing high quality software easily.
OOP will NOT • Design program for you • Prevent you from designing a bad program • Provide algorithms • Perform data management
Key Terms (cont.) • With OOP, we model the application domain with objects. • An object possesses • Data values or properties • Behavioral abilities or methods • Objects with similar attribute and method types comprise sets of objects called classes. • An object which is a member of a class is referred to as an instance of the class. • One object sends a message to another object asking it to do a particular task. The first object does not need to know how the task is done (only how to request that it be done). This corresponds to calling one of the second object’s methods!
4 major principles of OOP • Encapsulation • Abstraction • Inheritance • Polymorphism
1st major principle • Encapsulation
Implementation and Interface • In OOP, every class has two sides: • The implementation of the class - the data structures and code that implement its features. • The interface that the class exposes for use by other classes.
Client • We'll use the word “client” to refer to code that uses the public interface of a class and “implementation” when talking about the guts of a class. • With a good OOP design, the interface is smaller and simpler than the implementation. The public interface exposing only aspects that the clients care about and keeping the details of the implementation hidden away. • Client code will typically allocate objects and send them messages. • With good OOP design, being a client should be easy.
Implementation • Implementation - private, internal • How is the object implemented - how does it organizes its data into instance variables. • Methods - what data structures and code to do the actual implementation. • The word "detail" suggests some feature of issue of the implementation, but which the client does not need to know. It can be kept hidden inside the object - great! When someone says "that's a detail", they mean it's not something the client cares about.
Interface • Interface - public API, external • How does the object "expose" its abilities as public methods for use by client classes. • The interface must expose just the issues that are needed and relevant to the computation - keeping the implementation details hidden as much as possible. • The public interface/API should be organized for the convenience and needs of the clients. A great client interface may look quite different from the underlying implementation.
Example public class Rectangle { private String color; private int width; private int heigh; // Constructor public Rectangle(String c, int w, int h) { this.setColor(c); this.setWidth(w); this.setHeigh(h); } private void validateSize() … private void checkPosition() … private void setCanvas() … private void perform() … Implementation side Implementation side
Example // Draw the rectangle public String draw() { // May be some complex code here this.validateSize(); this.checkPosition(); this.setCanvas(); this.perform(); return "I'm a " + this.getColor() + " rectangle."; } // Calculate perimeter public int getPerimeter() { // May be some complex code here return 2 * (this.getWidth() + this.getHeigh()); } } Implementation side Implementation side Public interface Public interface
Example /* * Client side code * Being a client is so easy */ Rectangle red = new Rectangle("Red", 5, 8); // Simple send a message to draw System.out.println(red.draw()); // Send another message to get perimeter System.out.println("Perimeter is “ + red.getPerimeter()); Client side
2nd major principle • Abstraction
What is abstraction • Abstraction is the process by which data and programs are defined with a representation similar to its meaning (semantics), while hiding away the implementation details. • Abstraction tries to reduce and factor out details so that the programmer can focus on a few concepts at a time.
Abstraction • Abstraction is used to manage complexity. • Abstraction can apply to control or to data • Control abstraction is the abstraction of actions • Data abstraction is the abstraction of data structures.
Go abstraction • All Square, Rectangle, Circle and Triangle: • Have color • Can display • A shape may has all above characteristics, so we call “Shape” is an abstract type of Square, Rectangle, Circle and Triangle.
Abstract - Specific More abstract Shape Square Rectangle Circle Triangle More specific
Go abstraction (cont) • Then, we analysis deeper: • A rectangle has four sides with lengths w and h • A square has all of the characteristics of a rectangle; in addition, w = h • So, square is a type of rectangle, or, rectangle can be an abstract type of square
Abstract - Specific More abstract Shape Rectangle Square Circle Triangle More specific
Go abstraction (cont) • Please answer this question: • A circle has center and radius • A dot has all of the characteristics of a circle; in addition, radius = 0 • So, which is superclass and which is subclass?
3rd major principle • Inheritance
Inheritance • Ability of a new class to be created, from an existing class by extending it, is called inheritance.
Inheritance Vocabulary • OOP Hierarchy • Superclass / Subclass • Inheritance • Overriding • "isa“ - an instance of a subclass isa instance of the superclass.
General vs. Specific • The "super" and "sub" terms can be a little counterintuitive: • Superclass has fewer properties, is less constrained, is more general (confusingly, the word "super" can suggests a class with more properties) . • Subclass has more properties, is more constrained, is more specific.
Inheritance Warning • Inheritance is a clever and appealing technology. • However, it is best applied in somewhat rare circumstances - where you have several deeply similar classes. • It is a common error for beginning OOP programmers to try to use inheritance for everything. • In contrast, applications of modularity and encapsulation and API design may be less flashy, but they are incredibly common. • That said, for the cases where inheritance fits, it is a fantastic solution.
Inheritance Example Shape Circle Rectangle Color Center Radius Length Width getColor() setColor() draw() getPerimeter() getArea() getCenter() setCenter() getRadius() setRadius() draw() getPerimeter() getArea() getLenght() setLenght() getWidth() setWidth() draw() getPerimeter() getArea()
Inheritance Example • Circle and Rectangle inherit Shape, so Circle and Rectangle has Color property, which is inherited from Shape. • Shape is superclass. • Circle and Rectangle are subclasses. • Circle isa Shape, but Shape is not a Circle. • Method draw() in Circle overriding method draw() in Shape. • If we add/remove property to/from Shape, then it’s affected to Circle and Rectangle.
4th major principle • Polymorphism
Polymorphism • In object-oriented programming, polymorphism (from the Greek meaning "having multiple forms") is the characteristic of being able to assign a different meaning to a particular symbol or "operator" in different contexts. • Polymorphism means one name, many forms.
Polymorphism (cont) • The primary usage of polymorphism in industry is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer does not have to know the exact type of the object in advance, and so the exact behavior is determined at run-time.
Polymorphism example public abstract class Shape { private String Color; public Shape(String color) { this.setColor(color); } public String getColor() { return Color; } public void setColor(String color) { Color = color; } abstract public String draw(); }
Polymorphism example (cont) public class Circle extends Shape { public Circle(String color) { super(color); } @Override public String draw() { return "I'm a " + this.getColor() + " circle."; } } public class Rectangle extends Shape { public Rectangle(String color) { super(color); } @Override public String draw() { return "I'm a " + this.getColor() + " rectangle."; } }
Polymorphism example (cont) public class PolymorphismExample { private List<Shape> shapes = new ArrayList<Shape>(); public PolymorphismExample() { Shape myFirstCircle = new Circle("Red"); Circle mySecondCircle = new Circle("Blue"); Rectangle myFirstRectangle = new Rectangle("Green"); shapes.add(myFirstCircle); shapes.add(mySecondCircle); shapes.add(myFirstRectangle); } public List<Shape> getShapes() { return shapes; } public static void main(String[] args) { PolymorphismExample example = new PolymorphismExample(); for (Shape shape : example.getShapes()) { System.out.println(shape.draw()); } } }
Polymorphism example (cont) • Output : I'm a Red circle. I'm a Blue circle. I'm a Green rectangle.
Summary • Encapsulation • Abstraction • Inheritance • Polymorphism
Java OOP • Create new object type with class keyword. • A class definition can contain: • variables (fields) • initialization code • methods
Class Definition class classname { field declarations { initialization code } Constructors Methods }
Creating an Object • Defining a class does not create an object of that class - this needs to happen explicitly: classname varname = new classname(); • In general, an object must be created before any methods can be called. • the exceptions are static methods. • Sample code: SimpleClass and FooPrinter - FooPrinter can print the strings "FOO" and "foo"