Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
46 views

Classes Objects & Methods

A class is a template or blueprint that defines common properties and behaviors of objects. It contains data members, methods, constructors and blocks. An object is an instance of a class that has unique identity, state and behavior. To create an object, it must be declared, instantiated using the new keyword, and initialized. Constructors initialize a newly created object. The this keyword refers to the current object instance and is used to invoke constructors, methods and access data members of the current class. The garbage collector automatically removes objects from memory that are no longer referenced.

Uploaded by

Sonali Ekatpure
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Classes Objects & Methods

A class is a template or blueprint that defines common properties and behaviors of objects. It contains data members, methods, constructors and blocks. An object is an instance of a class that has unique identity, state and behavior. To create an object, it must be declared, instantiated using the new keyword, and initialized. Constructors initialize a newly created object. The this keyword refers to the current object instance and is used to invoke constructors, methods and access data members of the current class. The garbage collector automatically removes objects from memory that are no longer referenced.

Uploaded by

Sonali Ekatpure
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

CLASSES, OBJECTS &

METHODS
CLASS
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.

A class in java can contain:


•data member
•method
•constructor
•block
•class and interface

Syntax for class declaration:


class <class_name>{  
    data member;  
    method;  
}  
EXAMPLE OF CLASS
1. class Student1{  
2.  int id; //data member (also instance variable)  
3.  String name; //data member(also instance variable)  
4.   
5.  public static void main(String args[]){  
6.   Student1 s1=new Student1();//creating an object of Student  
7.   System.out.println(s1.id);  
8.   System.out.println(s1.name);  
9.  }  
10. }  
OBJECT IN JAVA
 An entity that has state and behavior is known as an object e.g.
chair, bike, marker, pen, table, car etc. It can be physical or
logical (tengible and intengible).
 The example of integible object is banking system.

 An object has three characteristics:

1. state: represents data (value) of an object.


2. behavior: represents the behavior (functionality) of an object
such as deposit, withdraw etc.
3. identity: Object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external
user. But,it is used internally by the JVM to identify each
object uniquely.
CREATING AN OBJECT
 There are three steps when creating an object from a
class:
1. Declaration: A variable declaration with a variable
name with an object type.
2. Instantiation: The 'new' key word is used to create the
object.
3. Initialization: The 'new' keyword is followed by a call
to a constructor. This call initializes the new object.
EXAMPLE FOR CREATION OF OBJECT
1. class Student1
2. {  
3.  int id;//data member (also instance variable)  
4.  String name;//data member(also instance variable)  
5.   
6.  public static void main(String args[]){  
7.   Student1 s1=new Student1();//
creating an object of Student  
8.   System.out.println(s1.id);  
9.   System.out.println(s1.name);  
10.  }  
11. }  
CONSTRUCTOR IN JAVA
 Constructor in java is a special type of method that is
used to initialize the object.
 Java constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object
that is why it is known as constructor.
 Rules for creating java constructor
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
 Types of java constructors

1. Default constructor (no-arg constructor)


2. Parameterized constructor
DEFAULT CONSTRUCTOR
 class Student{  
     int id;  

     String name;  

       

     Student(){  

     id = 0;  

     name = null;  

     }  

     void display(){System.out.println(id+" "+name);}  

    

     public static void main(String args[]){  

     Student s1 = new Student();  

         s1.display();  

      

    }  

 }  
PARAMETERIZED CONSTRUCTOR
 class Student4{  
     int id;  

     String name;  

       

     Student4(int i,String n){  

     id = i;  

     name = n;  

     }  

     void display(){System.out.println(id+" "+name);}  

    

     public static void main(String args[]){  

     Student4 s1 = new Student4(111,"Karan");  

     Student4 s2 = new Student4(222,"Aryan");  

     s1.display();  

     s2.display();  

    }  

 }  
CONSTRUCTOR OVERLOADING
 class Student5{  
     int id;  

     String name;  

     int age;  

     Student5(int i,String n){  

     id = i;  

     name = n;  

     }  

     Student5(int i,String n,int a){  

     id = i;  

     name = n;  

     age=a;  

     }  

     void display(){System.out.println(id+" "+name+" "+age);}  

    

     public static void main(String args[]){  

     Student5 s1 = new Student5(111,"Karan");  

     Student5 s2 = new Student5(222,"Aryan",25);  

     s1.display();  

     s2.display();  

    }  

 }  
‘THIS’ KEYWORD
1. this keyword can be used to refer current class instance
variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class
method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current
class instance.
1.TO REFER CURRENT CLASS INSTANCE VARIABLE.

 class Student11{
 int id;
 String name;

 Student11(int id,String name){


 this.id = id;
 this.name = name;
 }
 void display(){System.out.println(id+" "+name);}
 public static void main(String args[]){
 Student11 s1 = new Student11(111,"Karan");
 Student11 s2 = new Student11(222,"Aryan");
 s1.display();
 s2.display();
 }
 }
2. TO INVOKE CURRENT CLASS
CONSTRUCTOR
 class Student13{
 int id;
 String name;
 Student13(){System.out.println("default constructor is invoked");}

 Student13(int id,String name){


 this ();//it is used to invoked current class constructor.
 this.id = id;
 this.name = name;
 }
 void display(){System.out.println(id+" "+name);}

 public static void main(String args[]){


 Student13 e1 = new Student13(111,"karan");
 Student13 e2 = new Student13(222,"Aryan");
 e1.display();
 e2.display();
 }
 }
3. TO INVOKE CURRENT CLASS
METHOD
 class S{  
   void m(){  

   System.out.println("method is invoked");  

   }  

   void n(){  

   this.m();//no need because compiler does it for you.  

   }  

   void p(){  

   n();//complier will add this to invoke n() method as this.n()  

   }  

   public static void main(String args[]){  

   S s1 = new S();  

   s1.p();  

   }  

 }  
4. TO PASS ANARGUMENT IN A METHOD
 class S2{  
   void m(S2 obj){  

   System.out.println("method is invoked");  

   }  

   void p(){  

   m(this);  

   }  

     

   public static void main(String args[]){  

   S2 s1 = new S2();  

   s1.p();  

   }  

 }  
5. TO PASS ARGUMENT IN
CONSTRUCTOR CALL
 class B{  
   A4 obj;  

   B(A4 obj){  

     this.obj=obj;  

   }  

   void display(){  

     System.out.println(obj.data);//using data member of A4 class  

   }  

 }  

   

 class A4{  

   int data=10;  

   A4(){  

    B b=new B(this);  

    b.display();  

   }  

   public static void main(String args[]){  

    A4 a=new A4();  

   }  

 }  
COMMAND LINE ARGUMENTS
 The java command-line argument is an argument i.e.
passed at the time of running the java program.
 can pass N (1,2,3 and so on) numbers of arguments from
the command prompt.
EXAMPLE
1. class CommandLineExample{  
2. public static void main(String args[])
3. {  
4. System.out.println("Your first argument is: "+args[0
]);  }  
5. }  
 compile by > javac CommandLineExample.java
 run by > java CommandLineExample sonoo  

 Output: Your first argument is: sonoo


VARIABLE ARGUMENTS
 The varrags allows the method to accept zero or
muliple arguments.
 Syntax :

return_type method_name(data_type... variableName){}  
Rules for varargs :
 There can be only one variable argument in the
method.
 Variable argument (varargs) must be the last argument.
EXAMPLE
 class VarargsExample2{

 static void display(String... values){


 System.out.println("display method invoked ");

 for(String s:values){

 System.out.println(s);

 }

 }

 public static void main(String args[])

 {

 display();//zero argument

 display("hello");//one argument

 display("my","name","is","varargs");//four arguments

 }

}
 Output:display method invoked
 display method invoked
 hello
 display method invoked
 my
 name
 is
 varargs
GARBAGE COLLECTION
 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime
unused memory automatically. In other words, it is a way
to destroy the unused objects.
 To do so, we were using free() function in C language
and delete() in C++. But, in java it is performed
automatically. So, java provides better memory
management.
 Garbage collection is performed by a daemon thread
called Garbage Collector(GC). This thread calls the
finalize() method before object is garbage collected.
Advantage
 It makes java memory efficient because garbage
collector removes the unreferenced objects from heap
memory.
 It is automatically done by the garbage collector(a part
of JVM) so we don't need to make extra efforts.
OBJECT IS DEREFERENCED
1. By nulling a reference
 Employee e=new Employee();  

 e=null;  

2. By assigning a reference to another


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now object e1 is available forgarbage collection

3. By annonymous object
new Employee();  
FINALIZE() METHOD
 The finalize() method is invoked each time before the
object is garbage collected. This method can be used to
perform cleanup processing.
 The Garbage collector of JVM collects only those
objects that are created by new keyword. So if you
have created any object without new, you can use
finalize method to perform cleanup processing
(destroying remaining objects).

 Syntax
protected void finalize()
{ }
OBJECT CLASS
 The Object class is the parent class of all the classes in
java bydefault.
 In other words, it is the topmost class of java.

 The Object class is beneficial if you want to refer any


object whose type you don't know. Notice that parent
class reference variable can refer the child class object,
know as upcasting.
VISIBILITY CONTROL
 Public Access: Any variable or method is visible to the entire
class in which it is defined. But, to make a member accessible
outside with objects, we simply declare the variable or method
as public. A variable or method declared as public has the
widest possible visibility and accessible everywhere.
 Friendly Access (Default): When no access modifier is
specified, the member defaults to a limited version of public
accessibility known as "friendly" level of access. The
difference between the "public" access and the "friendly"
access is that the public modifier makes fields visible in all
classes, regardless of their packages while the friendly access
makes fields visible only in the same package, but not in other
packages.
 Protected Access: The visibility level of a "protected" field lies in
between the public access and friendly access. That is, the protected
modifier makes the fields visible not only to all classes and subclasses
in the same package but also to subclasses in other packages

 Private Access: private fields have the highest degree of protection.


They are accessible only with their own class. They cannot be inherited
by subclasses and therefore not accessible in subclasses. In the case of
overriding public methods cannot be redefined as private type.

 Private protected Access: A field can be declared with two keywords


private and protected together. This gives a visibility level in between
the "protected" access and "private" access. This modifier makes the
fields visible in all subclasses regardless of what package they are in.
Remember, these fields are not accessible by other classes in the same
package.
ARRAY
 array is a collection of similar type of elements that have
contiguous memory location.
 Java array is an object the contains elements of similar
data type
Types of Array
 Single Dimensional Array

 Multidimensional Array
SINGLE DIMESION ARRAY
 dataType[] arr; (or)  
 dataType []arr; (or)  

 dataType arr[];  

Initialization Of Array
arrayRefVar=new datatype[size];
MULTIDIMESION ARRAY
 dataType[][] arrayRefVar; (or)
 dataType [][]arrayRefVar; (or)

 dataType arrayRefVar[][]; (or)

 dataType []arrayRefVar[];

Initialization Of Array
int[][] arr=new int[3][3];//3 row and 3 column 
EXAMPLE OF ARRAY
 class Testarray{
 public static void main(String args[]){

 int a[]=new int[5];//declaration and instantiation


 a[0]=10;//initialization
 a[1]=20;
 a[2]=70;
 a[3]=40;
 a[4]=50;

 //printing array
 for(int i=0;i<a.length;i++)//length is the property of array
 System.out.println(a[i]);

 }}
STRING IN JAVA
 In java, string is basically an object that represents
sequence of char values.
 There are two ways to create String object:

1. By string literal
String s="welcome";  
2. By new keyword
String s=new String("Welcome");
STRING CLASS METHODS
char charAt(int index) returns char value for the particular index

int length() returns string length

String substring(int beginIndex) returns substring for given begin index

String substring(int beginIndex, int


returns substring for given begin index and end index
endIndex)

returns true or false after matching the sequence of


boolean contains(CharSequence s)
char value

int indexOf(int ch) returns specified char value index

String toLowerCase() returns string in lowercase.

String toUpperCase() returns string in uppercase.


boolean equals(Object another) checks the equality of string with object

boolean isEmpty() checks if string is empty

String concat(String str) concatinates specified string

String replace(char old, char new) replaces all occurrences of specified char value

replaces all occurrences of specified


String replace(CharSequence old, CharSeq
uence new) CharSequence

returns trimmed string omitting leading and


String trim()
trailing spaces

String split(String regex) returns splitted string matching regex


STRINGBUFFER CLASS
 A string buffer is like a String, but can be modified.
 It contains some particular sequence of characters, but
the length and content of the sequence can be changed
through certain method calls.
 They are safe for use by multiple threads.

 Every string buffer has a capacity.


STRINGBUFFER CLASS CONSTRUCTOR
StringBuffer()
1 This constructs a string buffer with no characters in it and an initial capacity of 16
characters.

StringBuffer(CharSequence seq)
2 This constructs a string buffer that contains the same characters as the specified
CharSequence.

StringBuffer(int capacity)
3 This constructs a string buffer with no characters in it and the specified initial
capacity.

StringBuffer(String str)
4
This constructs a string buffer initialized to the contents of the specified string.
STRINGBUFFER CLASS METHODS
 StringBuffer append(String str)
 This method appends the specified string to this
character sequence.
 int capacity()

 This method returns the current capacity.

 char charAt(int index)

 This method returns the char value in this sequence at


the specified index.
 int indexOf(String str)
 This method returns the index within this string of the
first occurrence of the specified substring.
 StringBuffer insert(int offset, char c)

 This method inserts the string representation of the char


argument into this sequence.
 StringBuffer replace(int start, int end, String str)

 This method replaces the characters in a substring of this


sequence with characters in the specified String.
 StringBuffer reverse()
 This method causes this character sequence to be
replaced by the reverse of the sequence.
 String substring(int start)

 This method returns a new String that contains a


subsequence of characters currently contained in this
character sequence
VECTOR CLASS
 The java.util.Vector class implements a growable array
of objects. Similar to an Array, it contains components
that can be accessed using an integer index.
VECTOR CLASS CONSTRUCTOR

Vector()
1 This constructor is used to create an empty vector so that its internal data
array has size 10 and its standard capacity increment is zero.

Vector(int initialCapacity)
2 This constructor is used to create an empty vector with the specified
initial capacity and with its capacity increment equal to zero.

Vector(int initialCapacity, int capacityIncrement)


3 This constructor is used to create an empty vector with the specified
initial capacity and capacity increment.
VECTOR CLASS METHODS
 void addElement(Object obj) Adds the specified
component to the end of this vector, increasing its size
by one.
 int capacity() Returns the current capacity of this vector.

 void copyInto(Object[] anArray) Copies the


components of this vector into the specified array.
 Object elementAt(int index) Returns the component at
the specified index.
 void clear() Removes all of the elements from this
Vector.
 int size() Returns the number of components in this
vector.
 int indexOf(Object elem) Searches for the first
occurence of the given argument, testing for equality
using the equals method.
 void insertElementAt(Object obj, int index) Inserts
the specified object as a component in this vector at the
specified index.
 Object lastElement() Returns the last component of the
vector.
 Object remove(int index) Removes the element at the
specified position in this Vector.
 void removeAllElements() Removes all components
from this vector and sets its size to zero.
ENUMERATION IN JAVA
 Enum in java is a data type that contains fixed set of
constants.
 It can be used for days of the week (SUNDAY,
MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc. The java enum
constants are static and final implicitly. It is available
from JDK 1.5.
 Java Enums can be thought of as classes that have fixed
set of constants.
EXAMPLE - ENUM
 class EnumExample1{  
 public enum Season { WINTER, SPRING, SUMMER, F
ALL }  
   

 public static void main(String[] args) {  

 for (Season s : Season.values())  

 System.out.println(s);  

   

 }}  
OUTPUT
WINTER
SPRING
SUMMER
FALL
INHERITANCE
 Inheritance can be defined as the process where one class acquires
the properties (methods and fields) of another.
 Extends keyword :

class Super{
.....
.....
}

class Sub extends Super{


.....
.....

}
TYPES OF INHERITANCE
 Single Inheritance
 Multilevel Inheritance

 Hierarchical Inheritance

 Multiple Inheritance( not in java)


 class Employee{  
  float salary=40000;  

 }  

 class Programmer extends Employee{  

  int bonus=10000;  

  public static void main(String args[]){  

    Programmer p=new Programmer();  

    System.out.println("Programmer salary is:"+p.salary);  

    System.out.println("Bonus of Programmer is:"+p.bonus);  

 }  

 }  
CONSTRUCTOR
 Constructor in java is a special type of method that is
used to initialize the object.
 Java constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object
that is why it is known as constructor.
 Rules
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
 Types Of Constructor

1. Default constructor (no-arg constructor)


2. Parameterized constructor
CONSTRUCTOR
 A special method automatically called when an object is
created by new()
 Java provide a default one that takes no arguments and
perform no special initialization
 Initialization is guaranteed
 All fields set to default values: primitive types to 0 and false,
reference to null
CONSTRUCTOR (CONT.)
 Must have the same name as the class name
So the compiler know which method to call
 Perform any necessary initialization
 Format: public ClassName(para){…}
 No return type, even no void!
It actually return current object
 Notice: if you define any constructor, with
parameters or not, Java will not create the
default one for you.
CONSTRUCTOR EXAMPLE

class Circle{
double r;
public static void main(String[] args){
Circle c2 = new Circle(); // OK, default constructor
Circle c = new Circle(2.0); //error!!
}
}
CONSTRUCTOR EXAMPLE
class Circle{
double r;
public Circle (double r) {
this.r = r; //same name!
}
public static void main(String[] args){
Circle c = new Circle(2.0); //OK
Circle c2 = new Circle(); //error!!, no more default
}
}

Circle.java:8: cannot resolve symbol


symbol : constructor Circle ()
location: class Circle
Circle c2 = new Circle(); //error!!
^
1 error
CONSTRUCTOR EXAMPLE
class Circle{
double r;
public Circle(){
r = 1.0; //default radius value;
}
public Circle (double r) {
this.r = r; //same name!
}
public static void main(String[] args){
Circle c = new Circle(2.0); //OK
Circle c2 = new Circle(); // OK now!
}
}

Multiple constructor now!!


Java Constructor Java Method

Constructor is used to initialize the state of Method is used to expose behaviour of an


an object. object.

Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default


Method is not provided by compiler in any
constructor if you don't have any
case.
constructor.

Constructor name must be same as the Method name may or may not be same as
class name. class name.
OVERRIDING
 What is overriding?

 The child class provides alternative implementation for


parent class method.

 The key benefit of overriding is the ability to define


behavior that's specific to a particular subclass type.

 Overridden method: In the superclass.

 Overriding method: In the subclass.


METHOD OVERRIDING
 Example:
 public class Car
 {
 public void maxSpeed()
 {
 System.out.println("Max speed is 60 mph");
 }
 }

 class Ferrari extends Car


 {
 public void maxSpeed()
 {
 System.out.println("Max speed is 120 mph");
 }
 public void msc(){}
 }
PUBLIC CLASS TESTCAR
{
 public static void main(String args[])
 {
 Ferrari f=new Ferrari();
 f.maxSpeed();
 }
 OR

 public static void main(String args[])


 {
 Car f=new Ferrari();
 f.maxSpeed();
 }
 }
INTRODUCTION TO OVERLOADING
 Same name, different arguments.
 Code deals with different argument types rather than
forcing the caller to do conversions prior to invoking
your method.
 It CAN have a different return type.
 Argument list MUST be different.
 Access modifier CAN be different.
 New exceptions can be declared.
 A method can be overloaded in the same class or in a
subclass.
IN SAME CLASS
 public class Sort
{

 public void sort2(int[] a )

{

 //Program to sort integers


}

 public void sort2(String[] a )


{

 //Program to sort Strings


}
 public class TestSort
 {
 public void arr()
 {
 int[] a={3,8,6,1,2};
 String[] s={"Sachin","Sourav","Dravid"};
 Sort s=new Sort();
 s.sort2(a);
 s.sort2(s);
 }

 public static void main(String[] args)


 {
 TestSort t=new TestSort();
 t.arr();
 }
 }
IN DIFFERENT CLASSES
 public class Sort
 {
 public void sort2(int[] a )
 {
 //Program to sort integers
 }
 }
 class FloatSort extends Sort
 {
 public void sort2(double[] a )
 {
 //Program to sort floats
 }
 public class TestSort
 {
 public void arr()
 {
 int[] a={3,8,6,1,2};
 double[] f={3.5,6.8,1.4,67.9};
 Sort s=new Sort();
 s.sort2(a);
 FloatSort s2=new FloatSort();
 s2.sort2(f);
 }

 public static void main(String[] args)


 {
 TestSort t=new TestSort();
 t.arr();
 }
 }
OVERLOADING VS. OVERRIDING
 Don't confuse the concepts of overloading and overriding

 Overloading deals with multiple methods in the same class with the same
name but different signatures

 Overriding deals with two methods, one in a parent class and one in a child
class, that have the same signature

 Overloading lets you define a similar operation in different ways for


different data

 Overriding lets you define a similar operation in different ways for


different object types

68
FINAL INSTANCE VARIABLES
 Principle of least privilege
 Code should have only the privilege and access it needs to
accomplish its task, but no more
 final instance variables
 Keyword final
 Specifies that a variable is not modifiable (is a constant)
 final instance variables can be initialized at their
declaration
 If they are not initialized in their declarations, they must be
initialized in all constructors

69
1 // Fig. 8.15: Increment.java
70
2 // final instance variable in a class.
OUTLINE
3
4 public class Increment
5 {
6 private int total = 0; // total of all increments  Increment.java
7 private final int INCREMENT; // constant variable (uninitialized)
8
9 // constructor initializes final instance variable INCREMENT Declare final
10 public Increment( int incrementValue ) instance
11 { variable
12 INCREMENT = incrementValue; // initialize constant variable (once)
13 } // end Increment constructor
14
15 // add INCREMENT to total
Initialize final instance
16 public void addIncrementToTotal() variable inside a constructor
17 {
18 total += INCREMENT;
19 } // end method addIncrementToTotal
20
21 // return String representation of an Increment object's data
22 public String toString()
23 {
24 return String.format( "total = %d", total );
25 } // end method toIncrementString
26 } // end class Increment
STATIC CLASS MEMBERS
 static fields
 Alsoknown as class variables
 Represents class-wide information
 Used when:
 all objects of the class should share the same copy of this instance variable
or
 this instance variable should be accessible even when no objects of the

class exist
 Can be accessed with the class name or an object name and a dot
(.)
 Must be initialized in their declarations, or else the compiler will
initialize it with a default value (0 for ints)

71
What is an Abstract class?

Superclasses are created through the process called


"generalization"
Common features (methods or variables) are factored out of object
classifications (ie. classes).
Those features are formalized in a class. This becomes the superclass
The classes from which the common features were taken become
subclasses to the newly created super class

Often, the superclass does not have a "meaning" or


does not directly relate to a "thing" in the real world
It is an artifact of the generalization process
Because of this, abstract classes cannot be instantiated
They act as place holders for abstraction
Abstract Class Example

In the following example, the subclasses represent


objects taken from the problem domain.
The superclass represents an abstract concept that
does not exist "as is" in the real world.

Abstract superclass: Vehicle Note: UML represents abstract


- make: String classes by displaying their name
- model: String in italics.
- tireCount: int

Car Truck
- trunkCapacity: int - bedCapacity: int
Defining Abstract Classes

Inheritance is declared using the "extends" keyword


If inheritance is not defined, the class extends a class called Object

public abstract class Vehicle


{ Vehicle
private String make; - make: String
private String model; - model: String
private int tireCount; - tireCount: int
[...]

public class Car extends Vehicle


Car Truck
{
- trunkCapacity: int - bedCapacity: int
private int trunkCapacity;
[...]

public class Truck extends Vehicle


{
private int bedCapacity; Often referred to as "concrete" classes
[...]
Abstract Methods

Methods can also be abstracted


An abstract method is one to which a signature has been provided, but
no implementation for that method is given.
An Abstract method is a placeholder. It means that we declare that a
method must exist, but there is no meaningful implementation for that
methods within this class

Any class which contains an abstract method MUST


also be abstract
Any class which has an incomplete method definition
cannot be instantiated (ie. it is abstract)
Abstract classes can contain both concrete and abstract
methods.
If a method can be implemented within an abstract class, and
implementation should be provided.
Abstract Method Example

In the following example, a Transaction's value can be


computed, but there is no meaningful implementation
that can be defined within the Transaction class.
How a transaction is computed is dependent on the transaction's type
Note: This is polymorphism.

Transaction
- computeValue(): int

RetailSale StockTrade
- computeValue(): int - computeValue(): int
Defining Abstract Methods

Inheritance is declared using the "extends" keyword


If inheritance is not defined, the class extends a class called Object

Note: no implementation
public abstract class Transaction
{
public abstract int computeValue(); Transaction
- computeValue(): int

public class RetailSale extends Transaction


{
public int computeValue() RetailSale StockTrade
{ - computeValue(): int - computeValue(): int
[...]

public class StockTrade extends Transaction


{
public int computeValue()
{
[...]

You might also like