Você está na página 1de 10

Introduction to Object Oriented Programming Part II

Objectives:
Reinforce the understanding of the students of their knowledge on classes and objects Introduce the concepts of encapsulation and data hiding Demonstrate the concept of inheritance Familiarize the students with superclass and subclasses Learn what and how polymorphism is used in object oriented programming

Introduction
So far, on the first part of the lesson you must have learned the concept of classes and also learned how to declare classes. Typically when creating a public class, the filename must match the class name of the Java program. //demonstrator.java public class demonstrator { //..codes } Java requires demonstrator class should be stored as demonstrator.java

Inheritance
Code reuse is one important feature in Object oriented programming. Object oriented design allows you to define relationships between classes that facilitate not only code reuse but also overall design by organizing classes and factoring in commonalities of various classes. Inheritance allows a class to inherit the attributes and methods of another class. This will allow the creation of brand new classes by abstracting the common attributes and behaviors.

Superclasses and Subclasses


The superclass or parent class contains all the attributes and behaviors that are common to classes that inherit from it. For example, in the case of Mammal class, all mammals have similar attributes such as eyeColor and hairColor, as well as behaviors such as generateInternalHeat and growHair. All mammals have these attributes and behaviors, so it is not necessary to duplicate them down the inheritance the inheritance tree for each type of mammal. The Mammal class is considered the superclass of the Dog and the Cat subclasses or child classes. In inheritance, when a subclass inherits from the superclass, it can do anything that the superclass can do. Each class will have methods and fields. Even though you dont need methods and fields to compile the program, it will be totally useless having a class without methods and/or fields.
public class classdemo { public static void main(String[] args) { System.out.println(Hello OOP students); } }

Polymorphism
In an inheritance hierarchy, all subclasses inherit from their superclass. However, because each subclass is a separate entity, each might require a separate response to the same message. For example, consider the Shape class and the behavior called Draw. When you tell somebody to draw a shape, the first questions asked is, What shape?. No one can draw a shape, as it is an abstract. You must specify a concrete shape. To do this, you must provide the actual implementation in Circle. Even though Shape has a Draw method, Circle overrides this method and provides its own Draw() method. Overriding basically means replacing an implementation of a parent with one from a child. For example, suppose you have an array of three objects Circle, Square and Star. Even though you treat them all as Shape objects, and send a Draw message to each Shape object, the end result is different for each because Circle, Square and Star provide the actual implementations. In short, each class is able to respond differently to the same Draw method and draw itself. public abstract class Shape { private double area; public abstract double getArea(); } The Shape class has an attribute called area that holds the value for the area of the shape. The method getArea() includes an identifier called abstract, a subclass must provide the implementation for this method; in this case, Shape, is requiring subclasses to provide to provide a get Area() implementation.

Creating a class called Circle and inherits from Shape (the extends keyword specifies that Circle inherits from Shape),
public class Circle extends Shape { double radius; public Circle(double r) { radius = r; } public double getArea() { area = 3.1416 * (radius * ); return (area); } } public class Rectangle extends Shape { double length; double width; public Rectangle(double l, double w) { length = l; width = w; } public double getArea() { area = length * width; return (area); } }

Creating Objects
An object is an instance of a class. To actually create an object we use the new operator.

public class classdemo2 { int i = 3; public static void main(String[] args) { classdemo2 obj1 = new classdemo2(); System.out.println("obj1.i = " + obj1.i); obj1.printHello(); classdemo2 obj2 = new classdemo2(); obj1.i = 5; System.out.println("obj1.i = " + obj1.i); obj1.printHello(); System.out.println("obj2.i = " + obj2.i); obj2.printHello(); } public void printHello() { System.out.println("Hello! i = " + i + "\n"); } }

From the code listing above we can observe that: We have a field named i of type integer and was initialize to 3 classdemo2 obj1 = new classdemo2(); creates an object from the classdemo2 classdemo2 obj2 = new classdemo2(); creates a second object from classdemo2

class instance is often used as a synonym for object classdemos new operator to actually allocate memory location for the object.

Declare And Access Fields and Methods Declaring fields


A field is an attribute declared in a class body. A field declaration in a Java program specifies the field name, the data type, optional expression (initializes the field), access specifiers and modifiers.
public class Employee { String name; double salary; int jobID; }

Access Specifiers
Access specifiers determines how accessible the field is to code in other classes from totally accessible to totally inaccessible. public, private, or protected are used to declare a field with this access modifiers. Without a declared access specifier, a field is accessible within its class and to all other classes within the same package.
public class Employee { int age; }

Only code contained in Employee and other classes declared in the same package as Employee can access age.
public class Employee { private double salary; }

salary field is declared as private, only code contained in its class can access the fields. salary becomes inaccessible to every other class in every package.
public class Employee { public String name; }

The code contained in Employee and all other packages classes can access name. Declaring every field in a given class public defeat the concept of information hiding. Suppose you created a car class to model a car and wheels, color, engine.
public class car

{ public Wheels Wheels; public String color; private Engine engine; }

Wheels and color are declare public because both of them are visible to an observer. However the engine declaration is private because engines are hidden inside the body of the car. public class Employee { protected String name; } A field declared as protected resembles a field with the default access level. The only difference between the two is that subclasses in any package can access the protected field. Only code contained in Employee, other classes declared in the same package as Employee and all Employees subclasses can access name.

Modifiers
You can optionally declare a field with a modifier keyword: final or volatile and/or static and/or transient.
class Employee { final int final int final int int jobId }

ACCOUNT = 1; PAYROLL_CLERK = 2; MANAGER = 3; = ACCOUNTANT;

Declaring a field with a final modifier, ensures that the field is initialized and subsequently treats the field as read-only variable. If you declare a field static, all objects share one copy of the field. When you assign a new value to that field, all objects can see the new value to that field. If static is not specified, the field is known as an instance field, and each object receives its own copy.
public class staticExample { public static int val = 0; staticExample() { ++val; } }

public class classdemo3 { public static void main(String[] args) { staticExample se = new staticExample(); System.out.println("se.val = " + se.val); staticExample se2 = new staticExample(); System.out.println("se2.val = " + se2.val); se2.val++; System.out.println("new se2.val = " + se2.val); System.out.println("se.val = " + se.val); } }

An instance field is a field declared without static keyword modifier. Instance fields are associated with objects -not classes. When modified by an objects code, only the associated class instance the object sees the change

Declaring Methods
OOP uses the term method to refer to the named bodies of code that are associated with classes. Methods describe the behaviors of either an object or a class. A method declaration consists of a method signature followed by a compound statement. The method signature specifies the methods name, return data type, parameter list, access specifiers, and the types of exceptions the method can throw.

Access Specifiers
The access specifiers public, private and protected determines how accessible the method is to code in other classes. Access ranges from totally callable to totally uncallable. If you do not declare a method with an access specifier keyword, Java assigns a default access to the method, making the method callable within its class and to all classes within the same package.
public class Temperature { private int degrees; void setDegree(int d) { degrees = d; } int getDegrees()

{ return degrees; } }

If you declare a method private, only code contained in its class can call that method.
public class MathUtilities { private int factorial(int n) { if(n==0) return 1; int product = 1; for(int i = 2; i <= n; i++) { product *= i; } return product; } int permutation(int n, int r) { return factorial (n) / factorial(n-r); } }

If you declare a method public, code contained in its class and other packages classes can call that method. public class Color { private int color; public int getColor() { return color; } }

If you declare a method protected, that method resembles a method with default access level. The only difference: subclasses in any package can access protected methods.
public class Employee { protected double computeSalary() {

return hoursWorked * hourlyRate; } }

Você também pode gostar