Method calls and Multiple Constructor

Internal method calls:
Example:
public class Outer
{
String ostr = “Outer”;

static String osstr = “Static Outer”;

Outer()
{
System.out.println(ostr);
}

class Inner
{
String istr = “Inner”;

Inner()
{
System.out.println(istr + “\t” + Outer.this.ostr);
}
}

static class Inners
{
String isstr = “Static Inner”;

Inners()
{
System.out.println(isstr + “\t” + Outer.osstr);
}
}

static Inners mess()
{
return(new Inners());
}

public static void main(String args[])
{
Outer.Inner ob = new Outer().new Inner();

Outer.Inners obs = Outer.mess();
}
}
External method calls:
public class Artist
{
private String name;
private Song song;

public Artist(String name)
{
this.name = name;
}

public String getName()
{
return this.name;
}

public void setName(String newName)
{
this.name = newName;
}

public Song getSongs()
{
System.out.println(this.song.listSongs());
}

public void addSong(String song)
{
songs.storeSong(song);
}
}

Multiple Constructor:
A class can have multiple constructors that assign the fields in different ways. Sometimes it’s beneficial to specify every aspect of an object’s data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.

Spot sp1, sp2;

void setup() {
size(640, 360);
background(204);
noLoop();
// Run the constructor without parameters
sp1 = new Spot();
// Run the constructor with three parameters
sp2 = new Spot(width*0.5, height*0.5, 120);
}

void draw() {
sp1.display();
sp2.display();
}

class Spot {
float x, y, radius;

// First version of the Spot constructor;
// the fields are assigned default values
Spot() {
radius = 40;
x = width*0.25;
y = height*0.5;
}

// Second version of the Spot constructor;
// the fields are assigned with parameters
Spot(float xpos, float ypos, float r) {
x = xpos;
y = ypos;
radius = r;
}
void display() {
ellipse(x, y, radius*2, radius*2);
}

}

 

Debugger

 Debugger:
A special program used to find errors (bugs) in other programs. A debugger allows a programmer to stop a program at any point and examine and change the values of variables.

Setting breakpoints:
Breakpoints are set with the break command (abbreviated b). The debugger convenience variable `$bpnum’ records the number of the breakpoint you’ve set most recently; see Convenience variables, for a discussion of what you can do with convenience variables.
You have several ways to say where the breakpoint should go.
break function
Set a breakpoint at entry to function function. When using source languages that permit overloading of symbols, such as C++, function may refer to more than one possible place to break. See section Breakpoint menus, for a discussion of that situation.
break +offset
break -offset
Set a breakpoint some number of lines forward or back from the position at which execution stopped in the currently selected stack frame. (See section Frames, for a description of stack frames.)
break linenum
Set a breakpoint at line linenum in the current source file. The current source file is the last file whose source text was printed. The breakpoint will stop your program just before it executes any of the code on that line.
break filename:linenum
Set a breakpoint at line linenum in source file filename.
break filename:function
Set a breakpoint at entry to function function found in file filename. Specifying a file name as well as a function name is superfluous except when multiple files contain similarly named functions.
break *address
Set a breakpoint at address address. You can use this to set breakpoints in parts of your program which do not have debugging information or source files.
break
When called without any arguments, break sets a breakpoint at the next instruction to be executed in the selected stack frame (see section Examining the Stack). In any selected frame but the innermost, this makes your program stop as soon as control returns to that frame. This is similar to the effect of a finish command in the frame inside the selected frame–except that finish does not leave an active breakpoint. If you use break without an argument in the innermost frame, GDB stops the next time it reaches the current location; this may be useful inside loops.
GDB normally ignores breakpoints when it resumes execution, until at least one instruction has been executed. If it did not do this, you would be unable to proceed past a breakpoint without first disabling the breakpoint. This rule applies whether or not the breakpoint already existed when your program stopped.
break … if cond
Set a breakpoint with condition cond; evaluate the expression cond each time the breakpoint is reached, and stop only if the value is nonzero–that is, if cond evaluates as true. `…’ stands for one of the possible arguments described above (or no argument) specifying where to break. See section Break conditions, for more information on breakpoint conditions.
tbreak args
Set a breakpoint enabled only for one stop. args are the same as for the break command, and the breakpoint is set in the same way, but the breakpoint is automatically deleted after the first time your program stops there. See section Disabling breakpoints.
hbreak args
Set a hardware-assisted breakpoint. args are the same as for the break command and the breakpoint is set in the same way, but the breakpoint requires hardware support and some target hardware may not have this support. The main purpose of this is EPROM/ROM code debugging, so you can set a breakpoint at an instruction without changing the instruction. This can be used with the new trap-generation provided by SPARClite DSU and some x86-based targets. These targets will generate traps when a program accesses some data or instruction address that is assigned to the debug registers. However the hardware breakpoint registers can take a limited number of breakpoints. For example, on the DSU, only two data breakpoints can be set at a time, and GDB will reject this command if more than two are used. Delete or disable unused hardware breakpoints before setting new ones (see section Disabling). See section Break conditions.
thbreak args
Set a hardware-assisted breakpoint enabled only for one stop. args are the same as for the hbreak command and the breakpoint is set in the same way. However, like the tbreak command, the breakpoint is automatically deleted after the first time your program stops there. Also, like the hbreak command, the breakpoint requires hardware support and some target hardware may not have this support. See section Disabling breakpoints. See also Break conditions.
rbreak regex
Set breakpoints on all functions matching the regular expression regex. This command sets an unconditional breakpoint on all matches, printing a list of all breakpoints it set. Once these breakpoints are set, they are treated just like the breakpoints set with the break command. You can delete them, disable them, or make them conditional the same way as any other breakpoint.
The syntax of the regular expression is the standard one used with tools like `grep’. Note that this is different from the syntax used by shells, so for instance foo* matches all functions that include an fo followed by zero or more os. There is an implicit .* leading and trailing the regular expression you supply, so to match only functions that begin with foo, use ^foo.
When debugging C++ programs, rbreak is useful for setting breakpoints on overloaded functions that are not members of any special classes.
info breakpoints [n]
info break [n]
info watchpoints [n]
Print a table of all breakpoints, watchpoints, and catchpoints set and not deleted, with the following columns for each breakpoint:
Breakpoint Numbers
Type
Breakpoint, watchpoint, or catchpoint.
Disposition
Whether the breakpoint is marked to be disabled or deleted when hit.
Enabled or Disabled
Enabled breakpoints are marked with `y’. `n’ marks breakpoints that are not enabled.
Address
Where the breakpoint is in your program, as a memory address.
What
Where the breakpoint is in the source for your program, as a file and line number.
If a breakpoint is conditional, info break shows the condition on the line following the affected breakpoint; breakpoint commands, if any, are listed after that.
info break with a breakpoint number n as argument lists only that breakpoint. The convenience variable $_ and the default examining-address for the x command are set to the address of the last breakpoint listed (see section Examining memory).

Primitive types and object types

By now, we are used to distinguishing between primitive values and objects. We know, for instance, that subtyping is provided for object types but not primitive types. In this chapter, we will focus a bit more in-depth on the differences between these two kinds of values. We will look at special types, called wrapper classes, that provide bridges between primitive values and objects. We will also study the difference between the way these two kinds of values are stored in memory, and the implication this difference has for the assignment statement. This will lead us to the concept of garbage collection, an important feature of Java.
Storing Object Values and Variables:
Object values and variables, however, are stored differently. Consider:
Integer I = new Integer (5);
Double D = new Double(5.5);
As before, both values and the variables are allocated memory. However, each assignment copies into the variable’s block, not the contents of the value block, but instead its address. All Java addresses are 1 word long, so all variables are allocated a 1-word block, regardless of their types. Thus, both the Double variable, D, and the Integer variable, I, are the same size, which was not the case with the double variable, d, and integer variable, i, we saw above.

All objects, however, are not of the same size. When a new object is created, a composite memory block consisting of a series of consecutive blocks, one for each instance variable of the object, is created. Thus, assuming an Integer has a single int instance variable, a block consisting of a single integer variable is created. Similarly, for a Double instance, a block consisting of a single double instance variable is created. The sizes of the two objects are different because of the difference in the sizes of their instance variable. However, in both cases, the object block consists of a single variable.

Now consider the following class:
public class APoint implements Point {
int x,y;
public APoint (int initX, int initY) {
x = initX; y = initY;
}
public void setX(int newVal) {
x = newVal;
}

}
The figure below shows how the following assignment of an instance of this class is processed:
Point P = new APoint( 50, 100) ;
An instance of this class has a memory block consisting of two consecutive int blocks, as shown in the figure.

 

Object Values and Variables:
Now consider the following subclass of APoint, called ABoundedPoint, that declares two APoint instance variables defining a rectangular area defining user-specified bounds of the point:
public class ABoundedPoint extends APoint {
APoint upperLeftCorner, lowerRightCorner;
public ABoundedPoint (int initX, int initY, Point initUpperLeftCorner, Point initLowerRightCorner) {
super(initX, initY);
upperLeftCorner = initUpperLeftCorner;
lowerRightCorner = initLowerRightCorner;
}

}
Recall that an instance has not only the instance variables defined in its class but also those defined the superclasses of its class. Therefore, an instance of ABoundedPoint, has a memory block consisting of memory blocks of four variables, two int variables, each of size 1 word, inherited from APoint, and two object variables, each also of size 1 word, defined in ABoundedPoint.

 

 

Class diagrams VS object diagrams

⦁ A class diagram is a graph of Classifier elements connected by their various static relationships. Note that a “class” diagram may also contain interfaces, packages, relationships, and even instances, such as objects and links. Perhaps a better name would be “static structural diagram”, but “class diagram” is shorter and well established.
⦁ An object diagram is a graph of instances, including objects and data values. A static object diagram is an instance of a class diagram; it shows a snapshot of the detailed state of a system at a point in time. The use of object diagrams is fairly limited, mainly to show examples of data structures.
⦁ Tools need not support a separate format for object diagrams. Class diagrams can contain objects, so a class diagram with objects and no classes is an “object diagram.” The phrase is useful, however, to characterize a particular usage achievable in various ways.

 

Abstraction and Modularization

 

Abstraction:

Abstraction in Java or Object oriented programming is a way to segregate implementation from interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class and Object.  Abstraction in Java is achieved by using interface and abstract class in Java. An interface or abstract class is something which is not concrete, something which is incomplete. In order to use interface or abstract class we need to extend and implement abstract method with concrete behavior. One example of Abstraction is creating interface to denote common behavior without specifying any details about how that behavior works e.g. You create an interface called Server which has start() and stop() method. This is called abstraction of Server because every server should have way to start and stop and details may differ. As I said earlier Abstraction in Java is implemented using abstract class and interface as discussed in next section. In fact What is abstraction in Java, Difference between Abstraction and Encapsulation  is also a very popular core Java interview because strong OOPS skill is one of the primary requirement for Java developers.
Abstraction Example:
A Car has Engine, wheels and many other parts. When we write all the properties of the Car, Engine, and wheel in a single class, it would look this way:
public class Car {

int price;
String name;
String color;
int engineCapacity;
int engineHorsePower;

String wheelName;
int wheelPrice;

void move(){
//move forward
}
void rotate(){
//Wheels method
}

void internalCombustion(){
//Engine Method
}

}
In the above example, the attributes of wheel and engine are added to the Car type. As per the programming, this will not create any kind of issues. But when it comes to maintenance of the application, this becomes more complex.
Abstraction has three advantages:
⦁ By using abstraction, we can separate the things that can be grouped to another type.
⦁ Frequently changing properties and methods can be grouped to a separate type so that the main type need not under go changes. This adds strength to the OOAD principle -”Code should be open for Extension but closed for Modification”.
⦁ Simplifies the representation of the domain models.
Applying the abstraction with composition, the above example can be modified as given below:

public class Car {

Engine engine = new Engine();
Wheel wheel = new Wheel();

int price;
String name;
String color;

void move(){
//move forward
}

}

public class Engine {
int engineCapacity;
int engineHorsePower;

void internalCombustion(){
//Engine Method
}

}

public class Wheel {
String wheelName;
int wheelPrice;

void rotate(){
//Wheels method
}

}
You can see that the attributes and methods related to the Engine and Wheel are moved to the respective classes.
Engine and Wheel are referred from the Car type. When ever an instance of Car is created, both Engine and Wheel will be available for the Car and when there are changes to these Types(Engine and Wheel), changes will only be confined to these classes and will not affect the Car class.

Modularization:

Modular programming is the approach where the application code is subdivided into separate subprograms, with each running a specific function or subroutine. These chunks of code can be split up and worked on by multiple programmers, teams or by an individual over time, with each chunk of code dedicated to doing on specific task. These tasks also become recyclable, as they can be tweaked to fit into other programs. This keeps a programmer from having to write a similar task again in the future if a module already exists in another location that can handle the task at hand. The programmer can simply pull out an existing module, tweak it and insert it into the new program he/she is working on, saving time and energy in his/her work.
If creating a program to track attendance in multiple classes at a school, the master program would achieve this task for all students in all classes, throughout the year. If the application were to be broken down into modules, one module might track the attendance for a specific student over the course of the year. Another module might group the student attendance records by class, such as Geology or Science class, or even sophomore class, junior class, or the class of 2009. The modularization of the program allows it to be applied to various scenarios, students, years, schools, or anywhere attendance needs to be tracked, simply by tweaking the existing code and making it fit into the new scenario.

 

Wrapper Classes In Java

Wrapper Classes:

Wrapper classes were introduced with the discussion of the primitive data types. Primitive values in Java are not  objects. In order to manipulate these values as objects, the java.lang package provides a wrapper class for each of the primitive data  types. All wrapper classes are final. The objects of all wrapper classes that can be instantiated are immutable, that is, their state cannot be  changed.

Although the Void class is considered a wrapper class, it does not wrap any primitive value and is not instantiable. It just denotes the Class object representing the keyword void.

In addition to the methods defined for constructing and manipulating objects of primitive values, the wrapper classes also define useful  constants, fields, and conversion methods.

When working with numbers, most of the time you use the primitive types in your code. For example:

int i = 500;
float gpa = 3.65f;
byte mask = 0xff;

There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapper classes for each of the primitive data types. These classes “wrap” the primitive in an object. Often, the wrapping is done by the compiler—if you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you.

All of the numeric wrapper classes are subclasses of the abstract class Number:

ammar

Primitive class 

int
char
float
boolean

Wrapper class coreesonding to their respective primitives 

Integer
Charecter
Float
Boolean

Example:

if(Character.isDigit(a[i]))
System.out.println(a[i] + “is a digit “);
if(Character.isLetter(a[i]))
System.out.println(a[i] + “is a letter “);

Byte class methods:

byteValue() – returns the Byte value as byte value
Ex : byte bvalue = Byte.byteValue();
parseByte() – returns byte value from a byte string
Ex: byte bvaue = Byte.parseByte(“93”);

Integer class methods:

intValue() – returns the Integer value as int value
Ex: int bvalue = Integer.intValue();
parseInt() – returns int value from a int string
Ex: int bvaue = Integer.parseInt(“73”);

Usage of Wrapper Classes:

They should be used in situations when primitives cannot be used. The main situation is when you want to store primitives in one of the Java collections (which cannot handle primitives).

The use of the wrapper classes is greatly simplified by something called autoboxing. This means that Java automatically determines whether a primitive or a corresponding wrapper should be used. So it’s rare that you need to use the wrapper classes explicitly.

Example:

ArrayList<Integer> al = new ArrayList<Integer>();

Integer is the wrapper for int. Thanks to autoboxing you can now store ints in the above Arraylist. Or rather Java will perform all necessary conversions back and forth between Integer and int.

Reason of using Wrapper Classes:

1) It is sometimes easier to deal with primitives as objects.
2) Moreover most of the collection classes store objects and not primitive data types.
3) The wrapper classes provide many utility methods also.
Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

POLYMORPHISM IN JAVA

Polymorphism:

The word Polymorphism means of many forms.In programming this word is meant to reuse the single code multiple times. In object oriented programming its a big question that why the Polymorphism is done, what is the purpose of it in our code?

There are lots of people who don’t even know the purpose and usage of Polymorphism.Polymorphism is the 3rd main pillar of OOP without it the object oriented programming is incomplete. Lets go in the depth of Polymorphism.

Why Polymorphism is done in OOP?

Its obvious that when we do inheritance between two classes, all the methods and properties of the first class are derived to the other class so that this becomes the child class which  adobes all the functionality of base class.It can also possesses its own separate methods.

But there is a big problem in inheriting the second class to the first class as it adobes all the methods same as the base class has,which  means that after inheritance both(base class& child class) have the methods of same name and same body as shown in this example:~
Base class:
public class fish
{
  public void eat()
   {
        console.writeline("fish eat");
    }
  public void swim()
   {
          console.writeline("fish swim");
    }
  }
Derieved Class:
class Dolphen:fish
{

  public void eat()
   {
        console.writeline("fish eat");
    }
  public void swim()
   {
          console.writeline("fish swim");
    }
}
In this example it is clear that when we Inherit two classes, all the methods with the same name and same body are adobed by the derived class as shown above.Both methods have the same name but if we change the body of the second method then it makes Compiler disturb whether to compile base class method or derived classes.
To remove this problem and to tell the compiler that which method is to be executed we need to use Polymorphism.

How the Polymorphism is done?

Polymorphism is used to remove the problem which is shown in the above code.It is done not by changing the name of the methods of both base & derived class.Infect it is done by adding the “virtual” keyword before the base class method, and the “override” keyword before the derived class method.As shown in this exmple:
Base Class:
public class fish
        {
            public virtual void eat()
            {
                Console.WriteLine("fish eat");
            }
            public virtual void swim()
            {
                Console.WriteLine("fish swim");
            }
        } 
 Derived Class:

class Dolphin : fish
        {

            public override void eat()
            {
                Console.WriteLine("Dolphin can eat");
            }
            public override void swim()
            {
                Console.WriteLine("Dolphin can swim");
            }
        }
This is actually the Polymorphism in which we write virtual keyword with the base class method and we write override keyword with the derived class method as we did. It helps the compiler to select the method to be executed.
Here is the complete code in which Polymorphism has been applied.
class Program
    {
        public class fish
        {
            public virtual void eat()
            {  }
            public virtual void swim()
            { }
            public virtual void dive()
            {}

        }
       public class Dolphin : fish
         {
            public override void eat()
            { Console.WriteLine("Dolphin eats Plants"); }
            public override  void swim()
            { Console.WriteLine("Dolphin swims quickly"); }
            public override  void dive()
            { Console.WriteLine("Dolphin dive deeply "); }
           public void dance()
            { Console.WriteLine("Dolphin can Dance"); }

        }
        public class Shark : fish
        {
            public override  void eat()
            { Console.WriteLine("Shark eats dead animal"); }
            public override  void swim()
            { Console.WriteLine("Sharks swim fastest than Dolphin"); }
            public override  void dive()
            { Console.WriteLine("Sharks Dive deeper than Dolphin"); }

            public void kill()
            { Console.WriteLine("Shark kills Others"); }

        }

        static void Main(string[] args)
        {
            Dolphin D = new Dolphin();
            D.dance();
            D.dive();
            D.eat();
            D.swim();
            Shark S = new Shark();
            S.kill();
            S.dive();
            S.eat();
            S.swim();
            Console.ReadLine();
        }
    }
Types of Polymorphism:
In general there are three types of polymorphism:
Overloading polymorphism:

Overloading polymorphism is where functions of the same name exist, with similar functionality, in classes which are completely independent of each other (these do not have to be children of the object class). For example, the complex class, the image class and the link class may each have the function “display”. This means that we do not need to worry about what type of object we are dealing with if all we want to do is display it on the screen.

Parametric polymorphism:

Parametric polymorphism is the ability to define several functions using the same name, but using different parameters (name and/or type). Parametric polymorphism automatically selects the correct method to be adopted according to the type of data passed in the parameter.

We can therefore define several addition() methods using the same name which calculates a sum of values.

  • The int addition(int,int) method would return the sum of two integers.
  • The float addition(float, float) would return the sum of two floats.
  • The char addition(char, char) would result as the sum of two characters as defined by the author.
  • etc.

signature is the name and type (static) given to the arguments of a function. Therefore it is a method’s signature which determines what is called on.

Inclusion polymorphism:

The ability to redefine a method in classes that are inherited from a base class is called specialization. One can therefore call on an object’s method without having to know its intrinsic type: this is inclusion polymorphism. This makes it possible to disregard the specialized class details of an object family, by masking them with a common interface (this being the basic class).

Imagine a game of chess, with the objects kingqueenbishopknightrook and pawn, each inheriting thepiece object.
The movement method could, using inclusion polymorphism, make the corresponding move according to the object class that is called on. This therefore allows the program to perform piece.movement without having to be concerned with each piece’s class.

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.

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”.