object oriented programming with java n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Object Oriented Programming with Java PowerPoint Presentation
Download Presentation
Object Oriented Programming with Java

Loading in 2 Seconds...

play fullscreen
1 / 46

Object Oriented Programming with Java - PowerPoint PPT Presentation


  • 156 Views
  • Uploaded on

Object Oriented Programming with Java. Written by Amir Kirsh, Edited by Liron Blecher. All that is to know on class syntax Constructors and Initializers Inheritance and Polymorphism Interfaces Nested Classes Casting Enums. Agenda. Classes and Objects. A class will look like this:

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Object Oriented Programming with Java' - alvis


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
object oriented programming with java

Object Oriented Programming with Java

Written by Amir Kirsh, Edited by Liron Blecher

agenda
All that is to know on class syntax
  • Constructors and Initializers
  • Inheritance and Polymorphism
  • Interfaces
  • Nested Classes
  • Casting
  • Enums
Agenda
classes and objects
Classes and Objects

A class will look like this:

<Access-Modifier> class MyClass { // field, constructor, and method declarations}

To instantiate an object we will do:

MyClass instance = new MyClass(<constructor params>);

accessibility options
Accessibility Options

Four accessibility options:– public – (default) = “package” **– protected * – private* protected is also accessible by package** called also “package-private” or “package-friendly”

Example:

public class Person {

privateString name;

protectedjava.util.Date birthDate;

String id; // default accessibility = package

public Person() {}

}

static

Called sometimes “class variable” as opposed to “instance variable”

Static

Static member can be accessed without an instance (same as in C++)

Example:

public class Widget {

static private int counter; static public getCounter() {return counter;}

}

int number = Widget.getCounter();

the this keyword
The ‘this’ keyword

In Java ‘this’ is a reference to myself(in C++ it is a pointer…)

Example:

public class Point {

private int x, y;

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

The ‘this’ keyword is also used to call another constructor of the same class – we will see that later

defining constants
Defining constants

Though const is a reserved word in Javait's actually not in use!However the final keyword let's you define constants and const variables

Example:

public class Thingy {

public final static int doodad = 6; // constant

public final int id; // constant variable

public Thingy(int id) {this.id = id;} // OK

//public void set(intid) {this.id = id;} // error!

}

agenda1
All that is to know on class syntax
  • Constructors and Initializers
  • Inheritance and Polymorphism
  • Interfaces
  • Nested Classes
  • Casting
  • Enums
Agenda
constructors
Constructors

– Constructors in Java are very similar to C++– You can overload constructors (like any other method)– A constructor which doesn't get any parameter is called “empty constructor”– You may prefer not to have a constructor at all, in which case it is said that you have by default an “empty constructor”– A constructor can call another constructor of the same class using the ‘this’ keyword– Calling another constructor can be done only as the first instruction of the calling constructor

Examples in following slides…

constructors1
Constructors

Example 1:

public class Person {

String name = ""; // fields can be initialized!

Date birthDate;

public Person() {} // empty constructor

public Person(String name) {

this(name, new Date()); //must be in first line

}

public Person(String name, Date birthDate) {

this.name = name;

this.birthDate = birthDate;

}

}

constructors2
Constructors

Example 2:

public class Person {

String name = "";

Date birthDate = new Date();

public Person(String name, Date birthDate) {

this.name = name;

this.birthDate = birthDate;

}

}

Person p; // OK

p = new Person(); // not good – compilation error

static initializer
Static Initializer

Static initializer is a block of instructions performed the first time a class is loaded

Static initializer may be useful to performa one time initializations of static members

Example:

public class Thingy {

static String s;

// the block underneath is a static initializer

static { s="Hello"; }

}

Usually static initializer would do a more complex job…

agenda2
All that is to know on class syntax
  • Constructors and Initializers
  • Inheritance and Polymorphism
  • Interfaces
  • Nested Classes
  • Casting
  • Enums
Agenda
inheritance
Inheritance

Some TermsA class that is derived from another class is called a subclass (also a derived class, extended class, or child class).

The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Excepting java.lang.Object, which has no superclass,every class has exactly one and only one direct superclass (single inheritance).In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

A class is said to be descended from all the classes in its inheritance chain stretching back to Object.

inheritance1
Inheritance

– Class Object is the ancestor base class of all classes in Java – There is no multiple inheritance in Java– Inheritance is always “public” thus type is not stated (no private or protected inheritance as in C++)– Class can implement several interfaces (contracts)– Class can be abstract– Access to base class is done using the super keyword– Constructor may send parameters to its base using the‘super’ keyword as its first instruction– If the base class does not have an empty constructor then the class is required to pass parameters to its super

Examples in following slides…

inheritance2
Inheritance

Example 1:

public class Person {

private String name;

public Person(String name) {

this.name = name;

}

// Override toString in class Object

public String toString() {

return name;

}

}

inheritance3
Inheritance

Example 1 (cont’):

public class Employee extends Person {

private Employee manager;

public Employee(String name, Employee manager) {

super(name); // must be first

this.manager = manager;

}

// Override toString in class Person

public String toString() {

return super.toString() + (manager!=null? ", reporting to: " + manager : " - I'm the big boss!");

}

}

inheritance4
Inheritance

Example 2:

abstract public class Shape {

protected Color line = Color.Black;

protected Color fill = Color.White;

protected Shape() {}

public Shape(Color line, Color fill) {

this.line= line;

this.fill= fill;

}

abstract public void draw();

abstract public booleanisPointInside(Point p);

}

inheritance5
Inheritance

Example 2 (cont’):

public class Circle extends Shape {

private Point center;

private double radius;

public Circle(Point center, double radius) {

this.center = center; this.radius = radius;

}

public void draw() {…} // use Graphics or Graphics2d

public booleanisPointInside(Point p) {

return (p.distance(center) < radius);

}

}

inheritance6
Inheritance

The final keyword is used to forbid a method from being override in derived classesAbove is relevant when implementing a generic algorithm in the base class, and it allows the JVM to linkage the calls to the method more efficientlyThe final keyword can also be used on a class to prevent the class from being subclassed at all

Example:

abstract public class Shape {

final public void setFillColor(Color color) {<some implementation>}

}

of course, final and abstract don‘t go together (why?)

interfaces
Interfaces

– Interface is a contract– An interface can contain method signatures (methods without implementation) and static constants– Interface cannot be instantiated, it can only be implemented by classes and extended by other interfaces– Interface that do not include any method signature is called a marker interface– Class can implement several interfaces (contracts)– Class can announce on implementing an interface, without really implementing all of the declared methods, but then the class must be abstract

Examples in following slides…

interfaces1
Interfaces

Example 1 – using interface Comparable:

// a generic max function

staticpublic Object max(Comparable... comparables) {

int length = comparables.length;

if(length == 0) { returnnull; }

Comparable max = comparables[0];

for(int i=1; i<length; i++) {

if(max.compareTo(comparables[i]) < 0) {

max = comparables[i];

}

}

return max;

}

// calling the function can go like this:

String maxStr = (String) max("hello", "world", "!!!");

interfaces2
Interfaces

Example 2 – supporting foreach on our own type:

To have your own class support iterating, using the "foreach“syntax, the class should implement the interface Iterable:

publicinterface Iterable<T> {

Iterator<T> iterator();

}

// example

publicinterface Collection<E> extends Iterable<E> {

Iterator<E> iterator();

}

interfaces3
Interfaces

Example 3 – supporting clone on our own type:

To have your own class support the clone methodthe class should implement the marker interfaceCloneable:

publicinterface Cloneable {}

interfaces4
Interfaces

Example 4 – new HasName interface:

To allow name investigation we want to create a new HasNameinterface:

publicinterface HasName {

String getName();

}

agenda3
All that is to know on class syntax
  • Constructors and Initializers
  • Inheritance and Polymorphism
  • Interfaces
  • Nested Classes
  • Casting
  • Enums
Agenda
nested classes
Nested Classes
  • Nested Classes are classes which are defined inside another class. They are divided into two categories:static and non-static.
  • Nested classes that are declared as static are simply calledstatic nested classesNon-static nested classes are called inner classes
  • Inner classes that are defined without having their own nameare called anonymous classes
  • All Nested classes have access to private data members and methods of the containing class (static nested class only have access to static methods and data members)
  • Examples in following slides…
nested classes1
Nested Classes

Example 1:

public class OuterClass {

private int a;

static public class InnerStaticClass {

public int b;

}

public class InnerClass {

public void setA(int a1) {

a = a1; // we have access to a !!!

}

}

}

nested classes2
Nested Classes

Example 1 (cont’):

OuterClass.InnerStaticClass obj1 =

new OuterClass.InnerStaticClass();

OuterClass.InnerClass obj2 =

new OuterClass().new InnerClass();

obj2.setA(3); // we modify a of OuterClass!!!

nested classes3
Nested Classes

Example 2 (Getting containing class ‘this’ reference):

public class OuterClass {

private inta;

public class InnerClass {

private inta;

public void setA(inta) {

a = a; //useless statement

this.a = a; //InnerClass’s instance a

//OuterClass’s instance a

OuterClass.this.a = a;

}

}

}

nested classes4
Nested Classes

Example 3 – anonymous class:

public interface HaveName{

String getName();

}

void someFunction(HaveNamesomeoneWithName) {

System.out.println(someoneWithName.getName());

}

public static void main(String[] args) {

someFunction(new HaveName() {

public String getName() { return "Momo"; }

});

}

agenda4
All that is to know on class syntax
  • Constructors and Initializers
  • Inheritance and Polymorphism
  • Interfaces
  • Nested Classes
  • Casting
  • Enums
Agenda
casting
Casting
  • When you want to convert an object of a superclass to one of its subclasses
  • Use only if you know for surewhat the objects’ class type
  • Use instanceofmethod to check the class type (can also be an interface or any class in the inheritance line)
  • If you fail to check, you might get a ClassCastException

Examples in following slides…

casting1
Casting

Example 1:

void foo() {

Object obj = new String(“Hiding in an object”);

boo (obj);

}

void boo(Object argument) {

if (argument instanceof String) {

String myString = (String)argument;

System.out.println (myString.toUpperCase());

}

}

agenda5
All that is to know on class syntax
  • Constructors and Initializers
  • Inheritance and Polymorphism
  • Interfaces
  • Nested Classes
  • Casting
  • Enums
Agenda
enums
Enums

Structure forConstant EnumerationNot an integer!- May represent data (= have fields)- May implement methods (member and static)Automatically extends the Enum abstract typeCannot extend other Classes or Enums,but can implement interfacesCannot be extended (Enums are final)

Examples in following slides…

enums1
Enums

Example 1:

publicclass Card {

publicenum Rank {DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,TEN, JACK, QUEEN, KING, ACE }

publicenum Suit {CLUBS, DIAMONDS, HEARTS, SPADES }

privatefinal Rank rank;

privatefinal Suit suit;

private Card(Rank rank, Suit suit) {this.rank = rank;this.suit = suit; }

enums2
Enums

Example 1 (cont’):

publicclass Card {

public String toString() { returnrank + " of " + suit; }

privatestaticfinal List<Card> deck =newArrayList<Card>();

// Initialize the static deck static {for (Suit suit : Suit.values()){for (Rank rank : Rank.values()){deck.add(newCard(rank, suit))}}; }

publicstaticArrayList<Card> newDeck() { // Return copy of prototype deckreturnnewArrayList<Card>(deck); }

}

enums3
Enums

Example 2:

publicenum Operation {

PLUS, MINUS, TIMES, DIVIDE;

// Do arithmetic op represented by this constant double eval(double x, double y) {

switch(this) {

casePLUS: return x + y;

caseMINUS: return x - y;

caseTIMES: return x * y;

caseDIVIDE: return x / y;

}

thrownew AssertionError("Unknown op: " + this);

}

}

enums4
Enums

Example 3:

publicenum Operation {

PLUS {double eval(double x, double y) { return x + y; } },

MINUS {double eval(double x, double y) { return x - y; } },

TIMES {double eval(double x, double y) { return x * y; } },

DIVIDE {double eval(double x, double y) { return x / y; } };

// Do arithmetic op represented by this constantabstractdouble eval(double x, double y);

}

links
Links
  • Core Java Interview Questions:
  • http://www.javacodegeeks.com/2013/09/core-java-interview-questions.html