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

Lecture 2 Fundamentals of Classes in Java

The document discusses object-oriented programming concepts like classes, objects, methods, and constructors in Java. It provides examples of how to define a class with attributes and methods, create objects from classes, add methods to classes, overload methods and constructors, and use constructors to initialize object attributes. Key concepts covered include defining classes with attributes and methods, creating objects from classes using the new keyword, calling methods on objects, passing parameters to methods, and returning values from methods.

Uploaded by

Gafeer Fable
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Lecture 2 Fundamentals of Classes in Java

The document discusses object-oriented programming concepts like classes, objects, methods, and constructors in Java. It provides examples of how to define a class with attributes and methods, create objects from classes, add methods to classes, overload methods and constructors, and use constructors to initialize object attributes. Key concepts covered include defining classes with attributes and methods, creating objects from classes using the new keyword, calling methods on objects, passing parameters to methods, and returning values from methods.

Uploaded by

Gafeer Fable
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Al-Farabi University College

Class Fundamentals
A class is a sort of template which has attributes and methods. An object is an instance of
a class, e.g. Riccardo is an object of type Person. A class is defined as follows:

class classname { // declare instance variables

type var1; type var2; // ...

type varN; // declare methods

type method1(parameters)
{ // body of method }

type method2(parameters)
{ // body of method }

// ... type methodN(parameters)


{ // body of method } }

The classes we have used so far had only one method, main(), however not all classes specify a
main method. The main method is found in the main class of a program (starting point of program).

Using the Vehicle class


class VehicleDemo {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
int range; // assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// compute the range assuming a full tank of gas
range = minivan.fuelcap * minivan.mpg;
System.out.println("Minivan can carry " + minivan.passengers + "
with a range of " + range); } }

Page 1
Al-Farabi University College

public class Vehicle {


int passengers;
int fuelcap ;
int mpg ;
}
Creating more than one instance
It is possible to create more than one instance in the same program, and each
instance would have its own parameters. The following program creates another
instance, sportscar, which has different instance variables and finally display the
range each vehicle can travel having a full tank.

class TwoVehicles {
public static void main(String args[]) {
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); } }

Page 2
Al-Farabi University College

Creating Objects
In the previous code, an object was created from a class. Hence ‘minivan’ was an
object which was created at run time from the ‘Vehicle’ class – vehicle minivan =
new Vehicle( ) ; This statement allocates a space in memory for the object and it also
creates a reference. We can create a reference first and then create an object:

Vehicle minivan; // reference to object only


minivan = new Vehicle ( ); // an object is created

Reference Variables and Assignment


Consider the following statements:

Vehicle car1 = new Vehicle ( );


Vehicle car2 = car 1;

We have created a new instance of type Vehicle named car1. However note that car2
is NOT another instance of type Vehicle. car2 is the same object as car1 and has
been assigned the same properties

car1.mpg = 26; // sets value of mpg to 26

If we had to enter the following statements:


System.out.println(car1.mpg);
System.out.println(car2.mpg);
The expected output would be 26 twice, each on a separate line.
car1 and car2 are not linked. car2 can be re-assigned to another data type:
Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
Vehicle car3 = new Vehicle();
car2 = car3; // now car2 and car3 refer to the same object.

Page 3
Al-Farabi University College

Methods
Methods are the functions which a particular class possesses. These functions
usually use the data defined by the class itself.
// adding a range() method
class Vehicle { int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// Display the range.
void range()
{ System.out.println("Range is " + fuelcap * mpg); }
}
Note that ‘fuelcap’ and ‘mpg’ are called directly without the dot (.) operator.
Methods take the following general form:
ret-type name( parameter-list )
{ // body of method }
‘ret-type’ specifies the type of data returned by the method. If it does not return any
value we write void. ‘name’ is the method name while the ‘parameter-list’ would be
the values assigned to the variables of a particular method (empty if no arguments
are passed).
class AddMeth {
public static void main(String args[]) {
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;

Page 4
Al-Farabi University College

System.out.print("Minivan can carry " + minivan.passengers + ".


"); minivan.range(); // display range of minivan
System.out.print("Sportscar can carry " + sportscar.passengers +
". ");
sportscar.range(); // display range of sportscar. }
}

Returning from a Method


When a method is called, it will execute the statements which it encloses in its curly
brackets, this is referred to what the method returns. However a method can be
stopped from executing completely by using the return statement
void myMeth()
{ int i;
for(i=0; i<10; i++)
{ if(i == 5) return; // loop will stop when i = 5
System.out.println();
} }
Hence the method will exit when it encounters the return statement or the closing
curly bracket ‘ } ‘

Methods which accept Parameters:


We can design methods which when called can accept a value/s. When a value is
passed to a method it is called an Argument, while the variable that receives the
argument is the Parameter.
// Using Parameters.
class ChkNum { // return true if x is even
boolean isEven(int x)
{ if((x%2) == 0)
return true;
else return false; } }
class ParmDemo {

Page 5
Al-Farabi University College

public static void main(String args[])


{ ChkNum e = new ChkNum();
if(e.isEven(10))
System.out.println("10 is even.");
if(e.isEven(9))
System.out.println("9 is even.");
if(e.isEven(8))
System.out.println("8 is even.");
} }
Output//
10 is even.
8 is even.
A method can accept more than one parameter. The method would be declared as
follows:
int myMeth(int a, double b, float c)
{ // ...
}
The following examples illustrates this:
class Factor {
boolean isFactor(int a, int b)
{ if( (b % a) == 0)
return true;
else return false;
} }
class IsFact {
public static void main(String args[]) {
Factor x = new Factor();
if(x.isFactor(2, 20))
System.out.println("2 is a factor.");
if(x.isFactor(3, 20))
System.out.println("this won't be displayed"); } }
Output//
2 is a factor.

Page 6
Al-Farabi University College

Constructors
A constructor is created by default and initializes all member variables to zero.
However we can create our constructors and set the values the way we want, e.g.
class MyClass {
int x;
MyClass()
{ x = 10; }
}
class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x); }
}
Output// 10 10

Constructor having parameters


We can edit our previous constructor to create a parameter:
MyClass(int i)
{ x = i; }
If we edit the main program, by changing the statements which initiate the two
objects:
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
Output// 10 88

Page 7
Al-Farabi University College

Overloading Methods and Constructors


The term overloading refers to the act of using the same method/constructor name
in a class but different parameter declarations. Method overloading is an example of
Polymorphism.

Method Overloading
// Demonstrate method overloading.
class Overload {
void ovlDemo() {
System.out.println("No parameters");
} // Overload ovlDemo for one integer parameter.
void ovlDemo(int a) {
System.out.println("One parameter: " + a);
} // Overload ovlDemo for two integer parameters.
int ovlDemo(int a, int b)
{ System.out.println("Two parameters: " + a + " " + b);
return a + b; } // Overload ovlDemo for two double parameters.
double ovlDemo(double a, double b)
{ System.out.println("Two double parameters: " + a + " "+ b);
return a + b; }
}
Main Program:
class OverloadDemo {
public static void main(String args[]) {
Overload ob = new Overload();
int resI; double resD; // call all versions of ovlDemo()
ob.ovlDemo();
System.out.println();
ob.ovlDemo(2);
System.out.println();
resI = ob.ovlDemo(4, 6);
System.out.println("Result of ob.ovlDemo(4, 6): " +resI);
System.out.println();

Page 8
Al-Farabi University College

resD = ob.ovlDemo(1.1, 2.32);


System.out.println("Result of ob.ovlDemo(1.1, 2.32): " + resD); }
}
Output// No parameters
One parameter: 2
Two parameters: 4 6
Result of ob.ovlDemo(4, 6): 10
Two double parameters: 1.1 2.32
Result of ob.ovlDemo(1.1, 2.32): 3.42

Automatic Type Conversion for Parameters of overloaded Methods


class Overload2 {
void f(int x)
{ System.out.println("Inside f(int): " + x); }
void f(double x)
{ System.out.println("Inside f(double): " + x); }
}
Main Program:
class TypeConv {
public static void main(String args[]) {
Overload2 ob = new Overload2();
int i = 10;
double d = 10.1;
byte b = 99;
short s = 10;
float f = 11.5F; ob.f(i); // calls ob.f(int)
ob.f(d); // calls ob.f(double)
ob.f(b); // calls ob.f(int) – type conversion
ob.f(s); // calls ob.f(int) – type conversion
ob.f(f); // calls ob.f(double) – type conversion }
}

Page 9
Al-Farabi University College

Output// Inside f(int): 10


Inside f(double): 10.1
Inside f(int): 99
Inside f(int): 10
Inside f(double): 11.5

Overloading Constructors
// Overloading constructors.
class MyClass { int x; MyClass() {
System.out.println("Inside MyClass().");
x = 0; }
MyClass(int i) {
System.out.println("Inside MyClass(int).");
x = i; }
MyClass(double d)
{ System.out.println("Inside MyClass(double).");
x = (int) d; }
MyClass(int i, int j)
{ System.out.println("Inside MyClass(int, int).");
x = i * j; }
}
Main Program
class OverloadConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass(88);
MyClass t3 = new MyClass(17.23);
MyClass t4 = new MyClass(2, 4);
System.out.println("t1.x: " + t1.x); System.out.println("t2.x: "
+ t2.x); System.out.println("t3.x: " + t3.x);
System.out.println("t4.x: " + t4.x); }
}

Page 10
Al-Farabi University College

Output// Inside MyClass().


Inside MyClass(int).
Inside MyClass(double).
Inside MyClass(int, int).
t1.x: 0
t2.x: 88
t3.x: 17
t4.x: 8

Access Specifiers: public and private


Whenever we started a class, we always wrote ‘public’. If one writes ‘class’ only,
by default it is taken to be public.
// Public and private access.
class MyClass {
private int alpha; // private access
public int beta; // public access
int gamma; // default access (essentially public
/* Methods to access alpha. Members of a class can access a private
member of the same class. */
void setAlpha(int a)
{ alpha = a; }
int getAlpha()
{ return alpha; } }
Main Program
class AccessDemo {
public static void main(String args[]) {
MyClass ob = new MyClass();
ob.setAlpha(-99);
System.out.println("ob.alpha is " + ob.getAlpha());
// You cannot access alpha like this:
// ob.alpha = 10; // Wrong! alpha is private!
// These are OK because beta and gamma are public.

Page 11
Al-Farabi University College

ob.beta = 88;
ob.gamma = 99; }
}

Page 12

You might also like