This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
2. Introduction
Java is a true object-oriented language and therefore the underlying
structure of all Java programs is classes.
A class is a template or prototype that defines a type of object.
Everything we wish to represent in a Java program must be
encapsulated in class.
Class defines the state and behavior of the basic programming
components known as objects.
A class defines the skeleton of an object.
Classes create objects and objects use methods to communicate
between them. This is all about object-oriented programming.
2
3. Contd.
A class is a blueprint that defines the states and the behaviors
common to all objects of a certain kind.
An object is a software bundle that has State and Behaviour.
1. An Object's state is stored in variables called fields.
2. An Object's behaviour is defined by its methods.
• Example 1: Dogs
• States: name, color, breed, and “is hungry?”
• Behaviors: bark, run, and wag tail
• Example 2: Cars
• States: color, model, speed, direction
• Behaviors: accelerate, turn, change gears
3
4. Defining a Class
A class is a user-defined data type with a template that serves to
define its properties.
Once a class type has been defined, we can create “variables” of
that type using declaration that are similar to the basic type
declarations.
In java such variables are known as instance variables, which are
the actual objects.
The basic form of a class definition is:
4
class classname [extends superclassname]
{
[ variable declaration; ]
[ methods declaration; ]
}
5. Contd.
Everything inside the square brackets [ ] is optional. This means the following would
be a valid class definition:
class Empty
{
}
classname and superclassname are any valid Java identifiers.
The keyword extends indicates that the properties of the superclassname class are
extended to the classname class. This concept is known as
inheritance.
5
6. Adding Variables (Fields)
Data is encapsulated in a class by placing data fields inside the
body of the class definition.
These variables are called instance variables (member variables)
because they are created when an object of the class is instantiated.
These variables are created exactly the same way as we declare
local variables.
Example:
class Rectangle
{
int length;
int width;
}
6
7. Adding Methods
A class with only data fields (and without methods that operate on
that data) has no life.
Methods are declared inside the body of the class but immediately
after the declaration of the instance variables.
The general form of a method declaration is:
7
type methodname(parameter-list)
{
method-body;
}
8. Contd.
Method declaration has four parts:
i. The name of the method (methodname).
ii. The type of the value the method returns (type).
iii. A list of parameters (parameter-list).
iv. The body of the method
The type specifies the type value the method would return. This
could be a simple data type such as int as well as any class type.
It could be void type, if the method does not return any value.
The methodname is a valid identifier.
The parameter-list is always enclosed in parenthesis and
contains variable names and types of all the values we want to
give to the method as input.
8
10. Creating Objects
An object in Java is essentially a block of memory that contains
space to store all the instance variables.
Creating an object also known as instantiating an object.
Objects in Java are created using the new operator.
The new operator creates an object of the specified class and
returns a reference to that object.
Syntax for object creation:
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the variable
10
12. Accessing class Members
To access members (fields and the methods) of an object use the
dot (.) operator together with the reference to an object.
The general syntax is as follows:
objectname.variablename;
objectname.methodname(parameter-list);
Example:
R1.length=23;
R1.width=13;
System.out.println(“Area is “+ R1.rectArea();
R1.getData(34,15);
System.out.println(“Area is “+ R1.rectArea();
12
a)
b)
13. 13
import java.util.*;
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}
// This class declares an object of type Vehicle.
class ObjectAndClass {
static int radius;
double Area;
void area(int r)
{
this.radius=r;
Area=3.14*radius*radius;
System.out.println("the area is "+Area);
}
public static void main(String[] args) {
Scanner cn=new Scanner(System.in);
ObjectAndClass obj1=new ObjectAndClass();
System.out.println("peasse enter the radius values");
radius=cn.nextInt();
obj1.area(radius);
14. 14
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// assign values to fields in sportscar
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
// compute the ranges assuming a full tank of gas
range1 = minivan.fuelcap * minivan.mpg;
range2 = sportscar.fuelcap * sportscar.mpg;
System.out.println("Minivan can carry " + minivan.passengers +
" with a range of " + range1);
System.out.println("Sportscar can carry " + sportscar.passengers +
" with a range of " + range2);
}
}
15. Constructors
It is possible to initialize objects they are created by:
Using the dot operator
The help of methods
But it would be simpler and more concise to initialize an object when it
is first created.
Java supports a special type of method, called a constructor, that
enables an object to initialize itself when it is created.
Constructors are special methods that are used to construct an instance
of a class.
A constructor initializes an object immediately upon creation. But
object creation only doesn’t call constructor rather it will be called
when the object is instantiated.
Call the constructor(s) preceding it with the new keyword.
15
16. Rules with Constructors
Class name and constructor name should be the same. That is, it has
the same name as the class in which it resides and is syntactically
similar to a method.
Constructors have no return type (not even void), this is because
they return the instance of the class itself.
Constructors should be public.
Constructors can not be inherited.
They can be overloaded. Many constructors with the same name can
be defined.
16
17. Types of Constructors
1. Default constructor: is the type of constructor with out any
argument.
2. Parameterized Constructor: is a constructor with one or more
argument.
When an instance of an object is created then the instance will call
the constructor.
It will be the default constructor which will be called, if there are no
any parameterized constructor.
But if there is any parameterized constructor, then it will be the
parameterized constructor with the specified parameter(s) which
will be called.
17
18. Default Constructor
• When you do not write a constructor in a class, it implicitly has a
constructor with no arguments and an empty body.
• But we can also have a default constructor with no parameter(s) as
follows:
class A
{
// Variable declaration and initialization
// Method definition
System.out.println(“Wlcome”);
}
class A{
public A()
{
System.out.println(“Wlcome”);
}
}
18
19. Parameterized Constructors
class employee
{
private String Ename, empno;
private float salary;
employee(String eno, String name, float sal)
{
empno = eno;
Ename= name;
salary = sal;
}
public void print()
{
System.out.prinln(empno+”t”+Ename+”t”+ salary);
}
}
public class demoEmp
{
public static void main(String args[])
{
Employee emp = new employee(“Au196/03”, “Jhon Micheal”, 2563.54);
}
} 19
20. this Keyword
• Instance can refer to itself with the keyword this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as
on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
}
20
21. Cascading Constructors
• A constructor can call another constructor with
this(arguments)
class LightSwitch {
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
21
22. Classes Recap
• Classes have fields to store the state of the objects in the class
and methods to provide the operations the objects can perform.
• We construct instances of a class with the keyword new
followed by a call a constructor method of the class.
• We can assign an instance to a variable with a datatype named
the same as the class.
• If you do not provide a constructor, the class will have one with
no arguments and no statements by default.
22
24. Apple Quiz
• What will these lines print out?
Apple a = new Apple("red", 100.0);
System.out.println(a.getColor());
System.out.println(a.getPrice());
a.setPrice(50.5);
System.out.println(a.getPrice());
Apple b = new Apple(74.6);
System.out.println(b.getColor());
System.out.println(b.getPrice());
b.setPrice(a.getPrice());
System.out.println(b.getPrice());
red
100.0
50.5
green
74.6
50.5t
24
25. Encapsulation
• Encapsulation: Hiding implementation details from clients.
• Encapsulation forces abstraction.
separates external view (behaviour) from internal view (state)
protects the integrity of an object's data
• Encapsulation is the technique of making the fields in a class private and
providing access to the fields via public methods. If a field is declared
private, it cannot be accessed by anyone outside the class, thereby
hiding the fields within the class. For this reason, encapsulation is also
referred to as data hiding.
• The main benefit of encapsulation is the ability to modify our
implemented code without breaking the code of others who use our
code. With this feature Encapsulation gives maintainability, flexibility
and extensibility to our code.
25
26. /* File name : EncapTest.java */
public class EncapTest
{
private String name;
private String idNum;
private int age;
}
The public methods are the access points to this class fields from the
outside java world. Normally, these methods are referred as getters and
setters. Therefore any class that wants to access the variables should
access them through these getters and setters.
Encapsulation cont..
26
27. public class EncapTest
{
private String name; private String idNum; private int age;
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public String getIdNum()
{
return idNum;
}
public void setAge( int newAge)
{
age = newAge;
}
public void setName(String newName)
{
name = newName;
}
public void setIdNum( String newId)
{
idNum = newId;
}
}
Encapsulation cont..
27
28. The variables of the EncapTest class can be access as below.
/* File name : RunEncap.java */
public class RunEncap
{
public static void main(String args[])
{
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+ " Age : "+
encap.getAge());
}
}
This would produce the following result:
Name : James Age : 20
Encapsulation cont..
28
29. Benefits of encapsulation
• Abstraction between object and clients
• Protects object from unwanted access
• The fields of a class can be made read-only or write-only.
• A class can have total control over what is stored in its fields.
• The users of a class do not know how the class stores its data. A class can
change the data type of a field and users of the class do not need to change
any of their code.
Encapsulation cont..
29
30. Inheritance
• Defining a new class based on an existing class is called derivation.
• The new class, or derived class, is referred to as a direct subclass of
the class from which it is derived.
• The original class is called a base class or superclass because it
forms the base for the definition of the derived class.
• You can also derive a new class from a derived class, which in turn
was derived from some other derived class, and so on.
• Java supports inheritance by allowing one class to incorporate
another class into its declaration. This is done by using the extends
keyword. Thus, the subclass adds to (extends) the superclass.
• The additional members that you define in the new class establish
what makes a derived class object different from a base class object.
30
31. • Any members that you define in the new class are in addition to those that
are already members of the base class.
• An inherited member of a derived class is a full member of that class and is
freely accessible to any method in the class.
• Objects of the derived class type will contain all the inherited members of
the base class—both fields and methods, as well as the members that are
specific to the derived class.
• Remember that a derived class object always contains a complete base class
object within it, including all the fields and methods that are not inherited.
• A major advantage of inheritance is that once you have created a superclass
that defines the attributes common to a set of objects, it can be used to create
any number of more specific subclasses. Each subclass can precisely tailor
its own classification.
• The following program creates a superclass called TwoDShape, which
stores the width and height of a two-dimensional object, and a subclass
called Triangle. Notice how the keyword extends is used to create a
subclass.
Inheritance cont..
31
32. // A class for two-dimensional objects.
class TwoDShape
{
double width, height;
void showDim()
{
System.out.println("Width and height are " +width + " and " + height);
}
}
// A subclass of TwoDShape for triangles.
class Triangle extends TwoDShape
{
String style;
double area()
{
return width * height / 2;
}
void showStyle()
{
System.out.println("Triangle is " + style);
}
}
Inheritance cont..
32
33. class Shapes
{
public static void main(String args[])
{
Triangle t1 = new Triangle();
Triangle t2 = new Triangle();
t1.width = 4.0; t1.height = 4.0; t1.style = "isosceles"; t2.width = 8.0; t2.height = 12.0;
t2.style = "right";
System.out.println("Info for t1: ");
t1.showStyle(); t1.showDim();
System.out.println("Area is " + t1.area());
System.out.println();
System.out.println("Info for t2: ");
t2.showStyle(); t2.showDim();
System.out.println("Area is " + t2.area());
}
}
Inheritance cont..
The output from this program is shown here:
Info for t1:
Triangle is isosceles
Width and height are 4.0 and 4.0
Area is 8.0
Info for t2:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0
33
34. Method overloading
• Defining two or more methods with the same name in
a class is called method overloading.
• The signature of each method in a class must be
distinct to allow the compiler to determine exactly
which method you are calling at any particular point.
The return type has no effect on the signature of a
method.
• You cannot differentiate between two methods just by
the return type. This is because the return type is not
necessarily apparent when you call a method.
34
35. public class mover
{
public static int method(int aa,int bb)
{
return aa+bb;
}
public static double method(double cc,double dd)
{
return cc+dd;
}
public static void main (String[] args)
{
int a=4,b=5;
double c=6.0,d=7.8;
System.out.println("sum of integer number is "+method(a,b));
System.out.println("sum of integer number is "+method(c,d));
}
}
Method overloading cont..
35
36. • In a class hierarchy, when a method in a subclass has the same return type and signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.
• When an overridden method is called from within a subclass, it will always refer to the version of
that method defined by the subclass.
• The version of the method defined by the superclass will be hidden.
• A subclass can call a constructor defined by its superclass by use of the following form of super:
• super(parameter-list); Here, parameter-list specifies any parameters needed by the constructor in
the superclass. super( ) must always be the first statement executed inside a subclass constructor.
class A
{
int i, j;
Public A(int a, int b)
{
i = a; j = b;
}
void show() {System.out.println("i and j: " + i + " " + j);}
}
Method overriding
36
37. class B extends A
{
int k;
Public B(int a, int b, int c)
{
super(a, b); k = c;
}
void show() {System.out.println("k: " + k);}
}
class Override
{
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
} The output produced by this program is shown here: k: 3
Method overriding cont..
37
38. • When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the version of show( ) inside B overrides the version declared in A.
• If you want to access the superclass version of an overridden method, you can do so by
using super.
class B extends A
{
int k;
Public B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
Method overriding cont..
38
39. Polymorphism
• Polymorphism is the ability of an object to take on many forms.
• The most common use of polymorphism in OOP occurs when a parent
class reference is used to refer to a child class object.
• In object-oriented programming, this refers to the ability of objects to
have many methods with different implementations.
• It is important to know that the only possible way to access an object is
through a reference variable.
• A reference variable can be of only one type. Once declared, the type
of a reference variable cannot be changed.
• The reference variable can be reassigned to other objects provided that
it is not declared final.
• The type of the reference variable would determine the methods that it
can invoke on the object.
• A reference variable can refer to any object of its declared type or any
subtype of its declared type. A reference variable can be declared as a
class or interface type.
39
40. class Bike
{
void run(){System.out.println("running");}
}
public class Splender extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}
public static void main (String[] args)
{
Bike b = new Splender();//upcasting
b.run();
}
}
Polymorphism cont..
40
41. Polymorphism cont..
public class Animal {
public void makeNoise()
{
System.out.println("Some sound");
}
}
class Dog extends Animal{
public void makeNoise()
{
System.out.println("Bark");
}
}
class Cat extends Animal{
public void makeNoise()
{
System.out.println("Meawoo");
}
}
public class Demo
{
public static void main(String[] args) {
Animal a1 = new Cat();
a1.makeNoise(); //Prints Meowoo
Animal a2 = new Dog();
a2.makeNoise(); //Prints Bark
}
}
41
42. Abstract class
An abstract class is a class that cannot be instantiated—we cannot
create instances of an abstract class.
One or more methods may be declared, but not defined. (The
programmer has not yet written code for a few methods).
The declared methods and classes have the keyword abstract in their
signature.
• Use the keyword abstract to declare abstract class and methods.
• A method labeled abstract is declared but not implemented
• Rule: An abstract class can have zero or more abstract methods
42
43. public abstract class Person
{
String name;
public Person(String n)
{
name = n;
}
public String getName()
{
return name;
}
public abstract String description();
}
Abstract Person Class
43
44. Abstract Classes cont..
Cannot instantiate or create an object of an abstract class but they can
be sub classed.
Person jacob = new Person("Jacob") // ERROR!!
• When an abstract class is sub classed, the subclass usually provides
implementations for all of the abstract methods in its parent class.
However, if it does not, then the subclass must also be
declared abstract.
An abstract class can have both abstract and non-abstract methods
• An abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon), like
this:
abstract void moveTo(double deltaX, double deltaY);
• If a class includes abstract methods, then the class itself must be
declared abstract
Abstract methods need to be defined in concrete subclasses (classes
that can be instantiated)
44
45. abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
Abstract Classes cont..
45
46. Interface
• An interface is a collection of abstract methods. A class implements an
interface, thereby inheriting the abstract methods of the interface.
• interface is similar to an abstract class except – all methods are abstract
automatically. An interface has no constructors, only variables and
methods.
• Interfaces specify but do not implement methods – provide function
declarations only.
• A class that implements the interface must implement all its methods
• You may then invoke methods on this class that rely on the interface.
• Interfaces can be inherited
public interface HelpfulConstants {
double OUNCE_TO_GRAM = 28.34;
double WATT_TO_HP = 745.1;
} 46
47. • An interface can be helpful to store constants in a program.
• A class uses the implements keyword to implement an interface.
• The variables in an interface are always public static final by default
so there is no need to specify any access modifiers.
public class MyProgram implements HelpfulConstants
{
public static void main(String[] args) {
System.out.println(“10 ounces equals: ” +(ONCE_TO_GRAM * 10)
+ “grams.”; }
}
• By implementing the HelpfulConstants Interface, MyProgram class
is able to access any variables defined in the interface.
Interface cont..
47
48. interface Animal {
public void eat(); public void travel();
}
public class Mammal implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Interface cont..
48