Download presentation
Presentation is loading. Please wait.
Published byShawn Hensley Modified over 6 years ago
1
Introduction to Programming G50PRO University of Nottingham Unit 9 : Classes and objects
Paul Tennent Room C7
2
Overview A more close look on classes and objects
A brief introduction to object-oriented programming in java
3
What Is a Class? A building unit of a java program
Your program may consist of multiple classes i.e.: you have been using the UserInput and String classes in many of your programs In object oriented programming a class is a blueprint or prototype from which objects are created.
4
Class Circle Example A class have three basic section
Fields : which represent any variables that will represent the object state Constructors: one or more constructor used to initialise an object on creation Methods: which should provide any functionality (behaviour) required by the object
5
Class Circle Example public class Circle { //class fields
private int x, y; private double radius; //constructors public Circle() { x = 0; y = 0; radius = 0; } public Circle (int ax, int ay, double aradius ) { x = ax; y = ay; radius = aradius;
6
Cont. Class Circle Example
//methods public void move(int newx, int newy){ x = newx; y = newy; } public void resize(double newRadius){ radius = newRadius; public void print(){ System.out.println("x:"+ x +" y:"+ y +" \nradius:"+ radius); } // end of class
7
What Is an Object? Java is object oriented programming language
Objects are key to understanding object-oriented technology real-world objects: television set, bicycle, car. objects have state and behavior
8
Using a Circle object A circle object is an instance of the circle class with an actual state We can change the state of the object using the offered methods //private fields x = 10 y = 15 radius = 2.5 move() print() resize() Methods (behavior)
9
Using a Circle object public class CircleDemo {
public static void main (String[] args){ System.out.println ("Circle 1"); Circle c1 = new Circle(); c1.print(); c1.move(2,2); c1.resize(3); System.out.println ("\n Circle 2"); Circle c2 = new Circle(5,7,2.5); c2.print() } // end of main }// end of class
10
Key points: new : is a java key word that is used to create an instance of a class with a specific state Using : Circle c1 = new Circle(); will: Call the Circle class constructor The constructor will initialize the Circle class fields (assign state to the object) c1 is a reference variable, it holds a reference that points to a circle object in memory We may use c1 to access any public fields / methods of the class
11
More on OOP in java object-oriented programming (OOP) is a programming paradigm that make use of "objects" to design applications and computer programs It is commonly used in mainstream software application development since the early 1990s A more detailed study of OOP is out of the scope of this course, for more details:
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.