8/3/2019 Declare Classes
1/41
Declare Classes
8/3/2019 Declare Classes
2/41
Abstract Class
An abstract class defines an abstractconcept which cant be instantiated. We
cant create object of abstract class, it can
only be inherited. Abstract class normallyrepresents concept with general actionsassociated with it.
8/3/2019 Declare Classes
3/41
Difference between abstract class and interfaces
Can have abstract methods and
concrete methods
All methods are not by defaultpublic
An abstract class can extendanother abstract class
The extended class canoverride the methods of itssuper class and its hierarchy
All abstract methods musthave abstract access modifier
Can have only methodsignatures and static finalmembers
All methods by default abstract
and public An interface can extend
another interface but not aclass
An implementing class can
implement multiple interfaces All methods in an interface
must not have abstract access
modifier
AbstractInterface
8/3/2019 Declare Classes
4/41
The following examples illustrate the differences:
abstract class Shape{
abstract void area();abstract void perimeter();void someMethod()// concrete method
{..
}}
interface Shape
{ void area();void perimeter();
}
8/3/2019 Declare Classes
5/41
Nested Classes
The Java programming language allowsyou to define a class within another class.Such a class is called a nested classand
is illustrated here:
class OuterClass
{ ... class NestedClass
{ ... }
}
8/3/2019 Declare Classes
6/41
Why Use Nested Classes?
It is a way of logically grouping classesthat are only used in one place.
It increases encapsulation.
Nested classes can lead to more readableand maintainable code.
8/3/2019 Declare Classes
7/41
Logical grouping of classesIf a class is useful to only one otherclass, then it is logical to embed it in that class and keep the twotogether. Nesting such "helper classes" makes their package morestreamlined.
Increased encapsulationConsider two top-level classes, A andB, where B needs access to members of A that would otherwise bedeclared private. By hiding class B within class A, A's members canbe declared private and B can access them. In addition, B itself canbe hidden from the outside world.
More readable, maintainable codeNesting small classes withintop-level classes places the code closer to where it is used.
8/3/2019 Declare Classes
8/41
Static Nested Classes
A static nested class is associated with itsouter class. And like static class methods,a static nested class cannot refer directly
to instance variables or methods definedin its enclosing class it can use themonly through an object reference.
8/3/2019 Declare Classes
9/41
Declare Enums
8/3/2019 Declare Classes
10/41
In prior releases, the standard way to represent an enumerated typewas the int Enum pattern:
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL = 3;
8/3/2019 Declare Classes
11/41
This pattern has many problems, such as:
Not typesafe - Since a season is just an int you can pass in anyother int value where a season is required, or add two seasonstogether (which makes no sense).
No namespace - You must prefix constants of an int enum with astring (in this case SEASON_) to avoid collisions with other int enum
types.
8/3/2019 Declare Classes
12/41
In 5.0, the Java programming language gets linguistic support for
enumerated types. In their simplest form, these enums look just liketheir C, C++, and C# counterparts:
enum Season { WINTER, SPRING, SUMMER, FALL }
8/3/2019 Declare Classes
13/41
Enum Example
public enum Day
{
SUNDAY, MONDAY, TUESDAY,WEDNESDAY, THURSDAY, FRIDAY,SATURDAY
}
8/3/2019 Declare Classes
14/41
Object Orientation
8/3/2019 Declare Classes
15/41
Inheritance Is-a, Has-a
In OO, the concept of IS-A is based onclass inheritance or interfaceimplementation.
For example, a Mustang is a type of horse,so in OO terms we can say, "Mustang IS-A
Horse." Subaru IS-A Car. Broccoli IS-AVegetable.
8/3/2019 Declare Classes
16/41
Example
public class Car {
// Cool Car code goes here
}
public class Subaru extends Car {
// Important Subaru-specific stuff goes here
// Don't forget Subaru inherits accessible Car memberswhich
// can include both methods and variables.
}
8/3/2019 Declare Classes
17/41
Has a
HAS-A relationships are based on usage,rather than inheritance.
A Horse IS-A Animal. A Horse HAS-AHalter.
public class Animal { }
public class Horse extends Animal {
private Halter myHalter;
}
8/3/2019 Declare Classes
18/41
Object Reference Type Casting
In java object typecasting one objectreference can be type castinto another object reference. The cast can be to its own class typeor to one of its subclass or superclass types or interfaces. There arecompile-time rules and runtime rules for casting in java.
There can be 2 casting java scenarios
Upcasting Downcasting
8/3/2019 Declare Classes
19/41
Return Type Declarations
Return Types on Overloaded Methods public class Foo {
void go() { } } public class Bar extends Foo { String go(int x) {
return null; } } NOT allowed to do is this:
8/3/2019 Declare Classes
20/41
Overriding and Return Types
Java 5, you're allowed to change the return type in the overriding method as long as the new return type is a subtype of the
declared return type of the overridden (superclass) method. class Alpha {
Alpha doStuff(char c) { return new Alpha(); } } class Beta extends Alpha {
Beta doStuff(char c) { // legal override in Java 1.5 return new Beta(); } }
8/3/2019 Declare Classes
21/41
Returning a Value
1. You can return null in a method with an object reference return type. public Button doStuff() { return null; } 2. An array is a perfectly legal return type. public String[] go() { return new String[] {"Fred", "Barney", "Wilma"}; } 3. In a method with a primitive return type, you can return any value or variable that can be implicitly converted to the declared return type. public int foo() {
char c = 'c'; return c; // char is compatible with int }
8/3/2019 Declare Classes
22/41
4. In a method with a primitive return type, you can return any value or variable that can be explicitly cast to the declared return type. public int foo () { float f = 32.5f;
return (int) f; } 5. You must not return anything from a method with a void return type. public void bar() { return "this is it"; // Not legal!! }
6. In a method with an object reference return type, you can return an object type that can be implicitly cast to the declared return type. public Animal getAnimal() { return new Horse(); // Assume Horse extends Animal }
public Object getObject() {
int[] nums = {1,2,3}; return nums; // Return an int array, // which is still an object }
8/3/2019 Declare Classes
23/41
Coupling and Cohesion
Cohesion and Coupling deal with the quality of an OO design.Generally, good OO design calls for loose coupling and highcohesion. The goals of OO designs are to make the application
Easy to Create
Easy to Maintain Easy to Enhance
8/3/2019 Declare Classes
24/41
Coupling
Coupling is the degree to which one classknows about another class. Let usconsider two classes class A and class B.
If class A knows class B through itsinterface only
8/3/2019 Declare Classes
25/41
High coupling
class DoTaxes {
float rate;
float doColorado() {
SalesTaxRates str = new SalesTaxRates();
rate = str.salesRate; // ouch
// this should be a method call:
// rate = str.getSalesRate("CO");
// do stuff with rate
}
}
8/3/2019 Declare Classes
26/41
class SalesTaxRates {
public float salesRate; // should be private
public float adjustedSalesRate; // should be private
public float getSalesRate(String region) {
salesRate = new DoTaxes().doColorado(); // ouchagain
// do region-based calculations
return adjustedSalesRate;
}
}
8/3/2019 Declare Classes
27/41
Cohesion
Cohesion is used to indicate the degree to which aclass has a single, well-focused purpose. Coupling is allabout how classes interact with each other, on the otherhand cohesion focuses on how single class is designed.
Higher the cohesiveness of the class, better is the OOdesign.
Benefits of Higher Cohesion: Highly cohesive classes are much easier to maintain and
less frequently changed. Such classes are more usable than others as they are
designed with a well-focused purpose
8/3/2019 Declare Classes
28/41
Low Cohesion
class BudgetReport {
void connectToRDBMS(){ }
void generateBudgetReport() { } void saveToFile() { }
void print() { }
}
8/3/2019 Declare Classes
29/41
Highly cohesion
class BudgetReport { Options getReportingOptions() { } void generateBudgetReport(Options o) { } } class ConnectToRDBMS {
DBconnection getRDBMS() { } } class PrintStuff { PrintOptions getPrintOptions() { } }
class FileSaver { SaveOptions getFileSaveOptions() { } }
8/3/2019 Declare Classes
30/41
Stack and Heap
the various pieces (methods, variables, andobjects) of Java programs live in one of twoplaces in memory: the stack or the heap.
For now, we're going to worry about only threetypes of things: instance variables, localvariables, and objects:
Instance variables and objects live on theheap.
Local variables live on the stack.
8/3/2019 Declare Classes
31/41
class Collar { }
class Dog {
Collar c; // instance variable
String name; // instance variable
public static void main(String [] args) {
Dog d; // local variable: d
d = new Dog();
d.go(d);
}
void go(Dog dog) { // local variable: dog c = new Collar();
dog.setName("Aiko");
}
void setName(String dogName) { // local var: dogName
name = dogName; }
}
8/3/2019 Declare Classes
32/41
Literal Values for All Primitive Types
'b' // char literal
42 // int literal
false // boolean literal 2546789.343 // double literal
These are primitive literals:
8/3/2019 Declare Classes
33/41
Integer Literals
There are three ways to represent
integer numbers in the Java
language: decimal (base 10), octal(base 8), and hexadecimal (base 16).
8/3/2019 Declare Classes
34/41
Octal Literals
Octal integers use only the digits 0 to 7. In Java,you represent an integer in octal form by placinga zero in front of the number, as follows:
class Octal {
public static void main(String [] args) { int six = 06; // Equal to decimal 6 int seven = 07; // Equal to decimal 7 int eight = 010; // Equal to decimal 8 int nine = 011; // Equal to decimal 9 System.out.println("Octal 010 = " + eight); } }
8/3/2019 Declare Classes
35/41
Hexadecimal Literals
Hexadecimal (hex for short) numbers areconstructed using 16 distinct symbols.
we use alphabetic characters to representthese digits.
Counting from 0 through 15 in hex lookslike this:
0 1 2 3 4 5 6 7 8 9 a b c d e f
8/3/2019 Declare Classes
36/41
class HexTest {
public static void main (String [] args) {
int x = 0X0001; int y = 0x7fffffff;
int z = 0xDeadCafe;
System.out.println("x = " + x + " y = " + y + " z= " + z
}
}
x = 1 y = 2147483647 z = -559035650
8/3/2019 Declare Classes
37/41
Primitive Casting
Casts can be implicit or explicit. An implicit cast meansyou don't have to write code for the cast; the conversionhappens automatically.
An implicit cast happens when you're doing a wideningconversion. In other words, putting a smaller thing (say,a byte) into a bigger container (like an int).
The large-value-into-small-container conversion isreferred to as narrowing and requires an explicit cast.
8/3/2019 Declare Classes
38/41
int a = 100;
long b = a;/ / implicit cast
float a = 100.001f;
int b = (int)a;// Explicit cast
8/3/2019 Declare Classes
39/41
Garbage collection
Garbage collection reclaims or free thememory allocated to objects that are nolonger to use. In other OO languages like
c++ , the programmer has to free memorythat is no longer to required. Failure to freethe memory can result in a number of
problems. Java automates the garbagecollection.
8/3/2019 Declare Classes
40/41
The garbage collector runs as a separatelow priority threads.
Gc() method invoke the garbage collector.
Turn off garbage collector using thisstatement.java -noasyncgc
The program is almost guaranteed to faildue to memory exhaustion.
8/3/2019 Declare Classes
41/41
The finalize method
Java provide a way to clean up a process before thecontrol return to the operating system.
protected void finalize() throws Throwable {}
Every class inherits the finalize() method
from java.lang.Object The method is called by the garbage collector when it
determines no more references to the object exist
The Object finalize method performs no actions but it
may be overridden by any class If overriding finalize() it is good programming practice touse a try-catch-finally statement and to alwayscall super. finalize()
Top Related