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

Java Classes and Objects Lesson 2025

The document provides an overview of Java classes and objects, explaining how classes serve as blueprints for creating objects with defined states and behaviors. It covers the creation of methods, constructors, and the differences between void and other data types, as well as how to instantiate objects and access their methods. Additionally, it includes examples and practice exercises to reinforce the concepts discussed.

Uploaded by

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

Java Classes and Objects Lesson 2025

The document provides an overview of Java classes and objects, explaining how classes serve as blueprints for creating objects with defined states and behaviors. It covers the creation of methods, constructors, and the differences between void and other data types, as well as how to instantiate objects and access their methods. Additionally, it includes examples and practice exercises to reinforce the concepts discussed.

Uploaded by

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

Java Classes and Objects

Classes in Java
• A class is a blueprint from which individual objects are created.
• Here we are going to see how we can create our own classes in Java and
define parameters within those classes.
• Previously we have seen that the parameters defined within a class defines
what the objects will be made of.
• In that case the state and behavior of objects expected to emanate from a
class are what we define as parameters within a class.
• Take an example of a class known as Dog.
• In this class we can have objects such as MyDog.
• MyDog can have state such as color, name, age
• It can also have behavior such as eating, barking, sleeping etc
• The class would be created as shown below
Java Code to Create A Class Known as Dog
public class Dog{ • All states are declared just like ordinary
String breed; variables in java.
int age; • Behavior is declared as a method in java.
String color; • A method in Java follows the following
syntax.
void barking(){ Datatype MethodName () {
} }
void hungry(){ • Inside the braces one can put what the
} method is expected to return or output.
void sleeping(){ • So in this case we have methods such as
Void barking () { }
}
}
Example two
• Lets create a class called car with Public Class car {
the following features. String color;
• State- color, brand, Model String Brand;
• Behavior- Move, stop, hoot. String Model;
Void Move (){ }
Void Stop() { }
Void hoot () { }
}
Cont.
• A class can have any of the types of variables. i.e Local variable,
Instance variable, etc.
• A class can have any number of methods to access the value of
various kinds of methods. In the example 1, barking(), hungry() and
sleeping() are methods.
• In order to make it possible for objects to be created from classes,
Java depends heavily on constructors.
• Lets look at methods and constructors more deeply.
Methods in Java
• A method is a block of code or collection of statements or a set of
code grouped together to perform a certain task or operation.
• They are also referred to as functions.
• It is used to achieve the reusability of code. We write a method once
and use it many times.
• We do not require to write code again and again. It also provides
the easy modification and readability of code, just by adding or
removing a chunk of code.
• The method is executed only when we call or invoke it.
• In classes and objects, methods are used to implement behaviors.
Creating A method
• A method must be declared within a class. It is defined with the name of
the method, followed by parentheses ().
• A method in Java follows the following syntax.
Public class ClassName{
Modifier Datatype methodName () {
}}
• Example think of a class known as cat with method sound.
public class Cat {
static void sound(){
System.out.println("Meow");
}
Cont.
• Modifiers include the following:
• Static
• Public
• Private
• If you omit the modifier (i.e fail to specify the modifier it takes public
modifier by default)
• For example sound(){} is the same as public sound (){}
• Note that it is advisable to use public only when you want to create
an instance (object of a class) where such is not the case always use
static.
Cont.
• This is so because static allows you to output the value of the method
without necessarily having to create an object of a class unlike public
and private in which you first have to create the object of a class.
• Note that when you use static, private or public together with the
void datatype you don’t need to have a return statement in the body
of the method to specify what the output will be. You can just use
Syestem.out.println()
• On the other hand if you use static, public, or private modifiers with
any other datatype you must have a return statement in the body.
Check the two examples in the next page.
Cont. Example to compare how we output from void datatype
and other datatypes

Any other datatype Void datatype


static String bark(){ static void bark(){
return ("woo! Wooo!"); System.out.println(“Woo! Wooo!);
} }
Two Two
public String bark(){ public void bark(){
return ("woo! Wooo!"); System.out.println(“Woo! Wooo!);
} }
Calling a method
• You call a method by referring to the method name in the main method.
Lets call the method we have created in the previous page.
public class Cat {
static void sound(){
System.out.println("Meow");
}
public static void main (String []args){
sound();
}}
The output of this program will be “Meow”
• As you may have noticed methods in Java are called in the same way as
functions in other programming languages.
Cont.
• Lets now use the String datatype in the same example rather than
void
public class Cat {
static String sound(){
return ("Meow");
}
public static void main (String []args){
System.out.println( sound() ); } }

The output of this program will be “Meow”


Creating More methods: A method to find the
maximum number between two numbers.
public class Java102 { public static void main (String []args) {
static double findMax(double a, double double height=10;
b){ double width=20;
double x; double x=findMax(height,width);
if (a>b){ System.out.println(x);
x=a; } }
else if (b>a){
x=b; }
}
else { x=0;}
return x;
}
Cont.
• The methods that you create in Java are highly influenced by the
nature of the task you want to perform.
• In the same way you create functions in other programming
languages.
• Practice Exercise
• Create a class known as dog with method bark.
• Create a class known as student with a method that gives pass if a student has
an average marks of 50% above.
What is a constructor
• A constructor in Java is a special method that is used to initialize objects.
• It has the same name as its class and is syntactically similar to a method.
However, constructors have no explicit return type.
• The constructor is called when an object of a class is created. It can be used
to set initial values for object attributes:
• All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member
variables to zero.
• However, once you define your own constructor, the default constructor is
no longer used.
Cont.
Class ClassName{
ClassName(){
}
}
• So here we can see that the
constructor shares the same name
as a class.
• Java allows two types of
constructors namely −
• No argument Constructors
• Parameterized Constructors
No Arguments Constructors
• The no argument constructors of Java does not accept any parameters instead, using
these constructors the instance variables of a method will be initialized with fixed values
for all objects.
• This is more of a static constructor since the value defined cannot change.
• The following is an example:
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
• In this example every object that is created from this class will have its value as 100
Parameterized Constructors
• Most often, you will need a constructor that accepts one or more
parameters.
• Parameters are added to a constructor in the same way that they are
added to a method, just declare them inside the parentheses after
the constructor's name.
• Thus this one is more dynamic. Check example in the next page
Cont.
class MyClass {
int x;

MyClass(int i ) {
x = i;
}
}
• In this constructor the value of i is not fixed since a user can pass any
value of x.
• Thus if you have two objects one you assign it the value of int x to be
20 and the other to be 50 this constructor will accept that.
Objects
• An object is created from a class. In Java, the new keyword is used to
create new objects.
• There are three steps when creating an object from a class:
• Declaration: A variable declaration with a variable name and an
object type.
• Instantiation: The 'new' keyword is used to instantiate or create the
object.
• Initialization: The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.
Example 1
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

public static void main(String []args){


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
The output of this code is: Passed Name is :tommy
Example 2:
public class Dog {
public Dog(String Name, String color){
System.out.println("The Dog's Name is:"+Name);
System.out.println("The Dog's Color is:" +color); }

public static void main(String[] args){


Dog myDog= new Dog("Bosco","Brown"); }
}
The output here is: The Dog’s Name is: Bosco
The Dogs color is: Brown
Example Three: Where you don’t declare
states inside the constructor
public class Puppy1 {
String color;
int age;
public Puppy1(){
}
public static void main(String[] args) {
Puppy1 mypuppy= new Puppy1();
mypuppy.color="white";
mypuppy.age=10;
System.out.println("The color is:"+mypuppy.color);
System.out.println("the age is:"+ mypuppy.age); } }
Accessing methods in a class
• Once you have created a method in a class to represent behavior you
can easily access it in an object.
• There is need to ensure that you use the right datatype when creating
the method.
• Void datatype means that nothing is returned thus the method is
empty. However if you use any other datatype it must have a return
value.
• To access the method you just create an object of a class then call the
method using the following syntax.
• Object.methodName();
• See example below
Example 3: Accessing Methods
public class Dog {
String color;
int age;
String bark(){
return("Woo! Woo!");
}
public Dog(){
}
public static void main(String[] args) {
Dog Bosco= new Dog( );
Bosco.color="Brown";
Bosco.age=5;
System.out.println("Bosco barks:"+Bosco.bark());
}}
Deciphering the program
• The program creates a class called Dog, it defines two states namely
name and age.
• It also has one method known as bark() which returns (“Woo!Woo!”)
• An object of class Dog is created whose name is Bosco. Then Bosco
implements the states as shown in blue color.
• Bosco also implements the methods as shown in red color
Practice Exercise
• Write a program to create a class called "Person" with the following
attributes: name, year of birth, and gender. Write a program to create
two instances of the "Person" class and print their details. Write a
program to create a method in the "Person" class to calculate the
person's age in years.

You might also like