INHERITANCE IN JAVA

Inheritance:

Inheritance is specific to object-oriented programming, where a new class is created from an existing class. Inheritance (often referred to as subclasses) comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. The main advantage of inheritance is the ability to define new attributes and new methods for the subclass which are then applied to the inherited attributes and methods. This can be used to create a highly specialized hierarchical class structure. The biggest advantage is that there is no need to start from scratch when wanting to specialize an existing class.

In inheritance where objects are defined by classes can inherit attributes and behavior from pre-existing classes called baseclasses, superclasses, or parent classes. The resulting classes are known as derived classes, subclasses, or child classes. The relationships of classes through inheritance give rise to a hierarchy.

Subclasses and super classes:

subclass or child class is a derivative class that inherits one or more languages entities from one or more other classes (called superclassesbase classes, or parent classes). The semantics of class inheritance vary from language to language, but commonly the subclass automatically inherits the instance variable and member functions of its superclasses. Some languages support the inhertance of other construct as well.

Class hierarchy:

The parent-child relationship between classes can be represented in a hierarchical view often called class tree view. The class tree view starts with a general class called superclass. Derived classes (child class or subclass) become more specialized further down the tree.

Multiple inheritance:

Some object oriented languages, such as C++ allow multiple inheritance, meaning that one class can inherit attributes from two superclasses. This method can be used to group attributes and methods from several classes into one single class.

 

Inheritance and controlling access:

You control access to variables, classes, functions, and methods using access control attributes.

Table1. Access control attributes

Access control attribute keyword Access
public available to any caller
private available only to the class that defines it
protected available only to the class that defines it and to any subclasses of that class
internal available to any caller within the same package

Methods that cannot be overridden:

Just as classes may be sealed/finalized method declarations may contain method modifiers that prevent the method from being overridden (i.e. replaced with a new function with the same name and type signature in a subclass). A private method is unoverridable simply because it is not accessible by classes other than the class it is a member function of.

Overriding:

Many object-oriented programming languages permit a class or object to replace the implementation of an aspect—typically a behavior—that it has inherited. This process is usually called overriding.

Overriding introduces a complication that which version of the behavior does an instance of the inherited class use—the one that is part of its own class, or the one from the parent (base) class? The answer varies between programming languages, and some languages provide the ability to indicate that a particular behavior is not to be overridden and should behave as defined by the base class.

Inheritance vs subtyping:

Subtyping enables a given type to be substituted for another type or abstraction. Subtyping is said to establish an is-a relationship between the subtype and some existing abstraction, either implicitly or explicitly, depending on language support. The relationship can be expressed explicitly via inheritance in languages that support inheritance as a subtyping mechanism. For example, the following C++ code establishes an explicit inheritance relationship between classes B and A, where B is both a subclass and a subtype of A, and can be used as an A wherever a B is specified (via a reference, a pointer or the object itself).

class A 
{ public:
   void DoSomethingALike() const {}
};

class B : public A 
{ public:
   void DoSomethingBLike() const {}
};

void UseAnA(A const& some_A)
{
   some_A.DoSomethingALike();
}

void SomeFunc()
{
   B b;
   UseAnA(b); // b can be substituted for an A.
}

In programming languages that do not support inheritance as a subtyping mechanism, the relationship between a base class and a derived class is only a relationship between implementations (a mechanism for code reuse), as compared to a relationship between types. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entail behavioral subtyping. It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected.

Error Handling

All Java errors are handled as exceptions. Exceptions extend the base class, Exception. You might have seen the try and catch block used. This is a way to “catch” exceptions – this essentially allowing you to handle various unexpected errors gracefully.

Life isn’t perfect. Much as we’d like to think otherwise, sometimes we encounter exceptional behavior. Things like missing files, badly formatted data to be parsed, and operations on null things are just a few of the many exceptions you may meet in your programming career. When these things happen, the JVM throws a temper tantrum, or (more technically) throws an exception.

How do you know if an exception could be thrown? The hard way is when the compiler complains that you didn’t properly handle the method. The easy way involves the API documentation. The standard API documentation on the Java site begins a method’s documentation with its header: the access level, return type, method name, parameters, miscellaneous modifiers, and the declared exceptions. For example, the readLine method in class java.io.BufferedReader throws IOException. Its header looks like this:

publicStringreadLine()throwsIOException
If a method might throw an exception, it has to declare that exception in its header using the throws statement. (Note: just because a method declares an exception doesn’t mean that it willthrow it, just that it might.) If you use a risky method, you have to tell the compiler what to do in case something bad happens. This is called catching the exception.

Design and Analysis

Class Design:

The preliminary design of a project is considered as one of the most significant parts of the project. You should adopt a strategy for planning tospend at least as much time working on the design as you plan to spend on theimplementation. Design of an application is not something that approaches before theprogramming – it is (the most significantchunk of) programming. Mistakes that arise in the code itself can later be fixed easily. Mistakes in the overalldesign can be, at best, expensive to put right and, at worst, fatal to the wholeapplication. In unlucky cases, they can be almost unfixable (short of starting all overagain).

User interface design:

As it matters with a well-designed application, this is pretty independent of the underlying logic of theapplication, so this can be done independently of designing the class structure for the rest of the project. BlueJ gives us the means of interacting with our application before a final user interface is available, so we can choose towork on the internal structure first.The user interface may be a GUI (graphical user interface) with menus and buttons, itcan be text based, or we can decide to run the application using the BlueJ method callmechanism.

Abstract Classes

Abstract classes:

Abstract classes in Java are classes which cannot be instantiated, meaning you cannot create new instances of an abstract class. The purpose of an abstract class is to function as a base for subclasses. This text gets into the purpose of abstract classes in more detail towards the end of this text. As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which implements that method:

// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println(“This is a concrete method.”);
}
}

class B extends A {
void callme() {
System.out.println(“B’s implementation of callme.”);
}
}

class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}

 

abstract class Demo {

// An abstract class may include abstract methods, which have no implementation.

abstract public int sum(int x, int y);

 

// An abstract class may also include concrete methods.

public int product(int x, int y) { return x*y; }

}

 

interface DemoInterface {

// All methods in an interface are abstract.

int getLength();

}

Object Oriented Programming

Chapter 4: Grouping objects

  •  Class libraries
  • Arrays List
  • Loops
  • While loop
  • For loop
  • Iterators
  • Has next
  • Next
  • Index access versus iterators

 

 

CHAPTER 8: IMPROVING STRUCTURE WITH INHERITANCE

  • Inheritance
  • Super class and sub class
  • Inheritance hierarchies
  • Coding of inheritance
  • Inheritance and access-rights
  •  Inheritance and initialization
  • Advantages of inheritance
  •  Avoiding code duplication
  •  Code reuse
  •  Easier maintenance
  • Extendibility
  • Subtyping
  • Subclasses and subtypes
  • Subtyping and assignment
  • Polymorphic variables
  • Polymorphic collections
  • Element types
  • Casting revisited
  • Wrapper classes 

CHAPTER 9: MORE ABOUT INHERITANCE

  • Static type and dynamic type
  • Overriding
  • Dynamic method lookup
  • Super call in methods
  • Method polymorphism
  • Object methods: toString
  • Protected access

Oop in java (post 3)

  • Creating Class

Class definition:

Assessor modifier Class CLas_Name

{

Fields;

Constructor;

Methods;

}

Fields:

you can set up variables outside of methods that all the methods in          your class  can see. These are known as Field variables (or Instance variables). You set them up in exactly the same way as any other variable.

 

Example:

Constructors:

java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

public class Cube1 { 

int length;

int breadth;

int height;

public int getVolume() {

return (length * breadth * height);

}

Cube1() {

length = 10;

breadth = 10;

height = 10;

}

Cube1(int l, int b, int h) {

length = l;

breadth = b;

height = h;

}

public static void main(String[] args) {

Cube1 cubeObj1, cubeObj2;

cubeObj1 = new Cube1();

cubeObj2 = new Cube1(10, 20, 30);

System.out.println(“Volume of Cube1 is : ” + cubeObj1.getVolume());

System.out.println(“Volume of Cube1 is : ” + cubeObj2.getVolume());

}

}

  Methods:

We clearly explain methods above.

 

  • Types of Statement

Assignment Statement:

An assignment statement in Java uses the assignment operator (=) to assign the result of an expression to a variable. In its simplest form, you code it like this:

variable = expression;

For example:

int a = (b * c) / 4;

compound assignment operator is an operator that performs a calculation and an assignment at the same time. All Java binary arithmetic operators (that is, the ones that work on two operands) have equivalent compound assignment operators:

Operator

Description

+= Addition and assignment
-= Subtraction and assignment
*= Multiplication and assignment
/= Division and assignment
%= Remainder and assignment

For example, the statement

a += 10;

is equivalent to

a = a + 10;

Condional Statement:

The && and || operators perform Conditional-AND and Conditional-OR operations on two Boolean expressions. These operators exhibit “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

&& Conditional-AND
|| Conditional-OR

 

  • Types of Methods

Accessor methods:

An accessor method is used to return the value of a private field. It follows a naming scheme prefixing the word “get” to the start of the method name. For example let’s add accessor methods for firstname, middleNames and lastname:

   //Accessor for firstName
   public String getFirstName()
   {
     return firstName;
   }

 

Mutator methods:

A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word “set” to the start of the method name. For example, let’s add mutator fields for address and username:

   //Mutator for address
   public void setAddress(String address)
   {
     this.address = address;
   }

 

  • Types of Variables

Local variables:

local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists.

Here’s a program that uses a local variable:

public class HelloApp
{
    public static void main(String[] args)
    {
        String helloMessage;
        helloMessage = "Hello, World!";
        System.out.println(helloMessage);
    }
}

You don’t specify static on a declaration for a local variable. If you do, the compiler generates an error message and refuses to compile your program.

 

Field variable:

Variable that are declared as a member of a class. OR Variables declared outside any method/constructor but inside the class block. We discuss this above in detail.

 

Parameters:

A parameter is a variable that you pass in to a function. If you think back to math class, you spend a lot of time talking about f(x). In that case, “f” is the function and “x” is the parameter- something passed in to x that is going to change what the output of f gives you.

For example, look at the code you’ve been using in every single Java program you’ve written:

public static void main(String[] args)

That is a function that takes one argument- an array of Strings that’s called args. Then there’s also the way you write stuff to the console:
System.out.println(“Hello World”);
In that case, you have a function that takes one parameter. The value of that parameter is the string “Hello World”.

Oop in java (post 2)

  • Method

A method is just a chunk of code that does a particular job. But methods are set out in a certain way. You have a method header, and a method body. The header is where you tell Java what value type, if any, the method will return (an int value, a double value, a string value, etc). As well as the return type, you need a name for your method, which also goes in the header. You can pass values over to your methods, and these go between a pair of round brackets.

A simple Java method requires a minimum of three items:

Visibility : public, private, protected
Return Type: void, int, double, (etc.)
name: whatever you want to call the method

Visibility means who can access it. If it is public, anyone who has access to your class file can access the method. In some circumstances, this is perfectly fine. If the method is private, only the functions inside of that class can call the method. This is used as utility methods to do something you do not want just anyone who uses the class to do. Protected gives public function to all child classes.

Return type is void if you do not want the method to give you any data back. It would be used for such things as a method that prints out something. Any other return requires a return statement with the type of data it returns. For example, if you add two integers and want the results of that integer, your return type would be int.

Name of the method is anything you choose that is not already used in the class (unless you are overloading the method which is beyond the scope of this article)

If you want the method to do something with the data you supply it, you also need to include parameters within the ( ) You include what data type it is and give that parameter a name (ie: you are declaring a local variable for that method only)
examples:

access   return type   name   parameters
public     void             add     (int a, int b)

This would be written

public void add(int a, int b)
{
// do stuff here
}

Since the return type is void, you will have to write what you want the method to do inside of the method such as by printing it out from the method

public void add(int a, int b)
{
System.out.println(a+b);
}

  • Source Code:

Code that is written in high level language is called source code and in the context of java its called java code and its extension is .java and it’s not directly run on computer compiler is required to convert it in machine code.

  • IDE(BlueJ):

BlueJ is an integrated development environment (IDE) for the Java programming language, developed mainly for educational purposes, but also suitable for small-scale software development.

BlueJ was developed to support the learning and teaching of object-oriented programming, and its design differs from other development environments as a result. The main screen graphically shows the class structure of an application under development (in an UML-like diagram), and objects can be interactively created and tested. This interaction facility, combined with a clean, simple user interface, allows easy experimentation with objects under development. Object-oriented concepts (classes, objects, communication through method calls) are represented visually and in its interaction design in the interface.

OOP in JAVA

Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts:

                                               Chapter 10

Abstract classes

Abstract methods

Multiple inheritance

Flexibility through abstraction

Interfaces

Multiple inheritance of interfaces

Interfaces as types

Interfaces as specifications

Chapter 11

Error Handling

Defensive programming

Client-server interaction

Argument checking

Server error reporting

Exception-throwing principles

Throwing an exception

Exception classes

            Unchecked exceptions

Exception handling

Checked exceptions: the throws clause

Catching exceptions: the try block

Throwing and catching multiple exceptions

Propagating an exception

 

                                                Chapter 12

 

Analysis and design

Class design

Designing class interfaces

User interface design

Documentation

Prototyping

Software growth models

Waterfall model

Iterative development model

Using design patterns

Structure of a pattern

Decorator

Singleton

Factory method

Observer

Pattern summary

OOP in Java

 

Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts:

  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Classes
  • Objects
  • Instance
  • Method
  • Message Parsing

 

  • Class:

In the real world, you’ll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

The following Bicycle class is one possible implementation of a bicycle:

 

class Bicycle {

 

int cadence = 0;

int speed = 0;

int gear = 1;

 

void changeCadence(int newValue) {

cadence = newValue;

}

 

void changeGear(int newValue) {

gear = newValue;

}

 

void speedUp(int increment) {

speed = speed + increment;

}

 

void applyBrakes(int decrement) {

speed = speed – decrement;

}

 

void printStates() {

System.out.println(“cadence:” +

cadence + ” speed:” +

speed + ” gear:” + gear);

}

}

 

  • Object:

Concept of object:

A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

Creating Object:

Here’s a small program, called CreateObjectDemo, that creates three objects: one Point object and two Rectangle objects. You will need all three source files to compile this program.


public class CreateObjectDemo {

public static void main(String[] args) {

// Declare and create a point object and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

// display rectOne's width, height, and area
System.out.println("Width of rectOne: " + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());

// set rectTwo's position
rectTwo.origin = originOne;

// display rectTwo's position
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);

// move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
}
}

This program creates, manipulates, and displays information about various objects. Here’s the output:

Width of rectOne: 100
Height of rectOne: 200
Area of rectOne: 20000
X Position of rectTwo: 23
Y Position of rectTwo: 94
X Position of rectTwo: 40
Y Position of rectTwo: 72