0% found this document useful (0 votes)
7 views

Chapter Java Inheritance and Abstract Classes

The document discusses object-oriented programming concepts in Java including inheritance, polymorphism, abstract classes, concrete classes, overriding methods, and special references like this and super. It provides examples of creating object instances from classes and subclasses that inherit and extend properties and behaviors.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter Java Inheritance and Abstract Classes

The document discusses object-oriented programming concepts in Java including inheritance, polymorphism, abstract classes, concrete classes, overriding methods, and special references like this and super. It provides examples of creating object instances from classes and subclasses that inherit and extend properties and behaviors.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Inheritance in Java

Eng. glmoyo
Object modelling
• Abstract object class – has undefined or incomplete methods (programme code)
Animal Cannot be fully defined or programmed here yet
because a particular animal hasn’t been chosen
Name: String
(identified/created/exemplified or instantiated)
This is just a higher stage (generalisation or
This method is definable at this indication that animals produce sound as one of
stage because it common to all their characteristics). At this stage animal
Eat() ProducesSound() code cannot run because its yet to
animals(they can inherit as it is):
ProduceSound() be written explicitly - under each particular animal
- Take_in_oxygen ()
Breath()
- Circulate_it_in_the_blood()
- Relearse_CO2() NB. Because of this (yet to be written code)
An abstract class contain one or more abstract methods or you CANNOT create new objects instances
programmes with incomplete code that is yet to be completed to from abstract classes like:
match a particular case or instance e.g. if the animal is to be a dog you Animal Dog = New Animal();
will add: Because what will it produce when you
ProduceSound() { write:
This makes it complete or concrete (animal)
Buck() ; } Dog.ProduceSound() its undefined ????
Object modelling
• Concrete object – all methods are defined (i.e. have complete code or programme)

Public Woman
(any one can utilise)
+Name: String + public: any class can use the feature (attribute or
Private operation);
(only she can use) -Teeth : integer # protected: any descendant of the class can use
the feature;
Protected #Mitochondrial_DNA : string - private: only the class itself can use the feature.
(only her and her kids)
ProduceSound() ProcuduceSound()
GiveBirth() {
Maternal inheritance Breath() Talk(), Cry(), Ululate()
(we all inherit this from our mothers) } (this is now particular to a human being ) thus we
repeat the same method in the supper class but
We inherit this as is so we do not write or rewrite the code override (i.e. modify or redefine or complete the code
for this method as it was already written in the supper class for) the part that was left abstract (incomplete) in the
animal object class
Relationship in classes
• Generally objects are related by nature
• The relationship can be expressed as shown below
Female
int Age Name of class
Base class String Gender Properties of a class
#Mitochondrial_DNA : string Operations of a class (class methods)
Breath()
ProduceSound() Inheritance (pointing line from subclass
superclass to superclass with unfilled arrow)

Extends The two subclasses inherit the property


Age and method Breath() ( without
subclass subclass
modification) – i.e. you find them being
Woman Goose
used in subclasses instances without
+Name: String +Name: String being re-declared and re-coded)
Derived -Teeth : integer -tomia : integer However the subclasses will redefine or
class ProduceSound() ProduceSound() override (i.e. modify ) the code for
GiveBirth() LayEggs() ProduceSound() method as the each do
Breath() Breath() it differently i.e. humans ---> talk ,
ducks ---> quack
Object oriented terminology
• Classes that inherit from another are called derived classes, subclasses, or subtypes.
• Classes from which other classes are derived are called base classes or super classes.
• A derived class is said to derive, inherit, or extend a base class.
• A subclass inherits variables and methods from its superclass and uses them without re-declaring
them (code re-use)
• Inheritance allows one class (the subclass) to use and modify the public variables and methods of
another class (the superclass). Usually, the subclass is a specialized version of the more general
superclass, an is-a relationship
• Polymorphism is writing code using a superclass that can be executed for any object of a subclass.
• Polymorphism refers to a programming language's ability to process objects differently depending
on their data type or class.
• There are two types of polymorphism in Java: compile-time polymorphism (where we can perform
method overloading) and runtime polymorphism (where we perform method overriding).
Instantiation and inheritance
INSTANCES: Female
Woman Bride = New Woman() int Age
Abstract
class #Mitochondrial_DNA : string
Bride: Woman
Super() {this.age=36}
+Name: Name = “Thandi” Breath(string AirType) {in = airType; out=“Co2”; return Out;}
-Teeth: Teeth = 32 ProduceSound() Abstract method
ProduceSound() Woman Goose
GiveBirth()
+Name: String +Name: String
Breath( AirType)
-Teeth : integer -beak_tomia : integer
Mother() Goose()
Woman Mother = New Woman() Concreate ProduceSound()
{ super();
Mother: Woman class {quack}
this.Name= “Martha”;
} LayEggs()
+Name: Name= “Martha”
ProduceSound(){talk()}
-Teeth: Teeth =32
ProduceSound(Mood){Cry()}
ProduceSound() GiveBirth() { if (pregnant) Overriding the abstract method
GiveBirth() return true else return false}
Breath( AirType)
Terminology of oop
• Overriding - a subclass can define a method that has exactly
the same method signature (arguments and return type) as a method
in its superclass. In that case, the method in the
subclass overrides the method in the superclass and effectively
replaces its implementation. Example:
• ProduceSound() is replaced by ProduceSound(){talk()} in sub class
• overloaded methods (i.e., methods with the same name but a
different number or type of arguments) in our example
1 version of produceSound() method:
st
• ProduceSound(){talk()} has no argument passed
• ProduceSound(Mood){Cry()} 2nd version of produceSound() method has an
argument -- > ‘mood’ – being supplied or passed
Special References:
• Special References: this and super
• this allow you to refer to the current object instance
• super allow you to refer to the members of the superclass
• Casting - explicitly tells the compiler to change the apparent type of an
object reference
• If there was a class called Mother and another called Bride with
• Bride Thandi = new Bride() ;
• Mother NewMother = new Mother();
• When Tandi joins mothers a year later, when she has her first child Tandi
has to change from Bride to be a new mother
• NewMother = (Mother) Tandi;
relationships
• Inheritance relationships
• How a class inherits methods and variables from its parent class
• Packaging
• How to organize objects into logical groups
• Inner classes
• A generalization of classes that lets you nest a class definition inside of another
class definition
• Subclassing and Inheritance
• Classes in Java exist in a class hierarchy. A class in Java can be declared as a
subclass of another class using the extends keyword. A subclass inherits variables
and methods from its superclass and uses them as if they were declared within
the subclass itself:
• Interfaces
• How to declare that a class supports certain behavior and define a
type to refer to that behavior
Mini JAVA project example
• Triangles
• There are 3 basic types of triangle. They all have 3 sides and are polygons.
1) Equilateral- Equilateral triangles have 3 equal sides and 3 equal angles of
60°
2) Isosceles - Isosceles triangles have 2 equal sides and 2 equal angles.
3) Scalene -Scalene triangles have no equal sides and no equal angles.
• The forth type can be
4) A Right-angled – with two sides intersection at 90° or right angle to each
other – how ever this can either be Scalene or Isosceles
• Design using JAVA OPP concepts a programme that finds the angles and
type of triangle given three sides
Conceptualizing the Triangle object
• Designing the Abstract triangle object (base class)- “ma triangles aka dai”
Abstract_Triangle 1) Defining Properties of triangles in general
Sides A,B,C : double Three variable to store sides data
Base class Angles A,B,C: double Three variables to store angles data
Area: double Variable Area to store the Area property
Triangle_Type: String Variable to store triangle type
Valid_Triangle: Boolean To indicate if given sides create a valid triangle
Abstract_Triangle(a,b,c)
Example of Invalid triangle {
SideA=a Superclass a, b, c
20cm 2cm SideB=b Constructor sideA sideC
SideC=c receives values,
Valid_Triangle = IsTriangleValid() a,b,c e.g. 5,6, 7 sideB
1cm } and puts them into
Constructor
Call a method which abstract void setAngles(); sides (i.e. it
checks if triangle is valid abstract double GetArea(); constructs the
triangle object
We cannot yet calculate area right now because we do not know the type of triangle it is. We thus show it is required for every
triangle but leave it incomplete(or abstract – not fully defined). Angles also are unknown , and also depend on the type of triangle
Right angled triangle
Abstract_Triangle
Sides A,B,C : double
Angles A,B,C: double
• As was discussed both Area: double
Isosceles and scalene Triangle_Type: String
triangles could be right Valid_Triangle: Boolean
angled Abstract_Triangle(a,b,c)
• thus this check on {
SideA=a
whether any of the SideB=b
angles is right angled SideC=c
could be performed in Valid_Triangle = IsTriangleValid()
the superclass }
• Thus the method IsRightAngled()
isRightAngled () is fully {
defined in the Check if hyp2= Opp2+adj2
superclass If true set area= ½ (opp x adj) Area = ½ base x per height
Return true
}
abstract void setAngles();
abstract double GetArea();
Code in Java for the super class
Abstract_Triangle
package triangleobjects_abstract_classes;
Sides A,B,C : double /** 9 * 10 * @author glmoyo 11 */ 12 13
abstract class Triangle_Abstract {
Angles A,B,C: double double SideA;
Area: double double SideB;
double SideC; Triangle attributes
Triangle_Type: String double AngleA;
double AngleB;
Valid_Triangle: Boolean double AngleC;
double Area;
Abstract_Triangle(a,b,c) boolean ValidTriangle;
String TriangleType;
{
SideA=a
public Triangle_Abstract (double A, double B, double C)
SideB=b { Constructor of triangle
SideC=c this.SideA=A;
this.SideB=B; (assigns values to triangle)
Valid_Triangle = IsTriangleValid() this.SideC=C;
ValidTriangle=isTriangle();
} }

IsRightAngled() private boolean isTriangle()


{ { An invalid triangle has
if((SideA>(SideB+SideC))||(SideB>(SideA+SideC))||(SideC>(SideB+SideA)))
Check if hyp2= Opp2+adj2 { one side (the longest
System.out.println("This is not a valid triangle");
If true set area= ½ (opp x adj) return false; side) greater than the
Return true else
}
sum of the other two e.g
} {
return true;
20, 5, 5 the sides won’t
abstract void setAngles(); } touch
}
abstract double GetArea();
Code in Java for the super class
Abstract_Triangle public boolean isRightAngled()
{ If A side is hypotenuse
if(SideA*SideA==(SideB*SideB+SideC*SideC))
Sides A,B,C : double {
Angles converted from radians to
Angles A,B,C: double AngleA= Math.toDegrees(Math.PI/2);
AngleB = Math.toDegrees(Math.asin(SideB/SideA));
degrees
Area: double AngleC = Math.toDegrees(Math.asin (SideC/SideA));
System.out.println("This is Right angled triangle Side A is largest, B is " + SideB +" A is "+ SideA + " and B/A is "+ SideB/SideA);
Triangle_Type: String Area=SideB*SideC/2;
TriangleType =TriangleType + " Right Angled";
Valid_Triangle: Boolean return true;
}
If B side is hypotenuse
Abstract_Triangle(a,b,c) if (SideB*SideB==(SideA*SideA+SideC*SideC))
{
{ AngleB= Math.toDegrees(Math.PI/2);
AngleA = Math.toDegrees(Math.asin (SideA/SideB));
SideA=a AngleC = Math.toDegrees(Math.asin (SideC/SideB));
System.out.println("This is Right angled triangle Side B is largest");
SideB=b Area=SideA*SideC/2;
SideC=c TriangleType =TriangleType + " Right Angled";
return true; If B side is hypotenuse
Valid_Triangle = IsTriangleValid() }
if (SideC*SideC==(SideB*SideB+SideA*SideA))
} {
AngleC= Math.toDegrees(Math.PI/2);
IsRightAngled() AngleA = Math.toDegrees(Math.asin (SideA/SideC));
AngleB = Math.toDegrees(Math.asin (SideB/SideC));
{ System.out.println("This is Right Angled triangle Side C is largest");
Check if hyp2= Opp2+adj2 Area=SideA*SideB/2;
TriangleType =TriangleType + " Right Angled";
If true set area= ½ (opp x adj) }
return true;

Return true else return false else If triangle is not right


{
} System.out.println("This is Not a Right angled triangle "); angled
TriangleType =TriangleType + " Not Right Angled";
abstract void setAngles(); return false;
abstract double GetArea(); }
}
Code in Java for the super class
Abstract_Triangle
Sides A,B,C : double
Angles A,B,C: double
Area: double
Triangle_Type: String
Valid_Triangle: Boolean
Abstract_Triangle(a,b,c)
{
SideA=a
SideB=b
SideC=c
Valid_Triangle = IsTriangleValid()
}
IsRightAngled() These two makes this class an abstract class because they are
{ declared but no code is provided to depict their action in this
Check if hyp2= Opp2+adj2 superclass (higher class)
If true set area= ½ (opp x adj) Lower classes will inherit them and redefine their methods
Return true else return false individually (a process called overriding)
} This is like you inherit teeth making from your mother but the
abstract void setAngles(); actual teeth you produce are actually different (not exactly like
abstract double GetArea(); hers). You are overriding your mothers genes
Representing the Triangle objects
Abstract_Triangle
• Generally below
Sides A,B,C : double 1) Defining Properties of triangles in general
Angles A,B,C: double
Area: double
Properties of a triangle (data about
Triangle_Type: String
triangle) used for its construction
Base class Valid_Triangle: Boolean
Abstract_Triangle(a,b,c) Constructor for triangle (fully defined)
IsRightAngled() Check if triangle is right angled (fully defined)
IsTriangleValid() Test validity of sides of triangle (fully defined)
abstract double GetArea()
superclass Just stated but has incomplete code or code not
abstract void setAngles();
fully defined. It is said to be abstract (no clear
Extends implementation as yet) for now, here
subclass subclass subclass
Isosceles Scalene Equilateral
Inherits these features Inherits features Inherited features
Derived
class setAngles() {θB = θC =sin-1 (A/2B) setAngles() {θA = cos-1 (B2+C2-A2)/(2BC))} Constructor (A,B,C)
ΦA=180-2θB} GetArea(){ s= ½(a+b+c) { super (A,B,C)}
GetArea(){ double h=B*sin B Area= 𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐) setAngle() {Angle A,B,C =60}
Return 0.5*h*SideA } } Area() × 𝑠𝑖𝑑𝑒
public class Isosceles_triangle extends Triangle_Abstract {

Isosceles Triangle code


public Isosceles_triangle (double A, double B, double C)
{
super (A,B,C); Isosceles triangle
} constructor calls the
@Override
public void setAngles() Triangle_Abrastract
{
double h;
constructor -its parent or its
Inheriting from Triangle_Abstract using if (false==super.isRightAngled()) superclass using key word
{
keyword extends Isosceles triangle if (SideB==SideC) super <– here using tittle ref
{
Isosceles constructor AngleB=Math.acos((SideA)/(2*SideB));
AngleC=AngleB;
AngleA= Math.PI-2*AngleB;
Other inherited features h=SideB*Math.sin(AngleB);
Area= 0.5*h*SideA;
Isosceles_triangle (A, B, C) }
Sets angles and else if (SideA==SideC)
{
area using AngleA=Math.acos((SideB)/(2*SideA));
setAngles() { AngleC=AngleA;
these formulae AngleB= Math.PI-2*AngleC;
θB = θC =sin-1 (A/2B) h=SideC*Math.sin(AngleC);
Area= 0.5*h*SideB;
ΦA=180-2θB} }
GetArea(){ The if…else
else // SideB=SideA
{
double h=B*sin B statement check
AngleA=Math.acos((SideC)/(2*SideA));
AngleB=AngleA;
Return ½h*A which sides of the AngleC= Math.PI-2*AngleA;
h=SideA*Math.sin(AngleA); 48 Area= 0.5*h*SideC;
} isosceles are the }
AngleA=Math.toDegrees(AngleA);
same between A, B AngleB=Math.toDegrees(AngleB);
AngleC=Math.toDegrees(AngleC);
and C in order to }
Override parent method
}
apply the formula @Override
of getting the Area ( this
correctly public double GetArea()
{ means “I want to use my
return Area;
} own method”
Scalene Triangle code package triangleobjects_abstract_classes; /** * *
@author glmoyo */
public class Scalene_triangle extends
Triangle_Abstract {
Inheriting from Triangle_Abstract using public Scalene_triangle (double A, double B, double
keyword extends Scalene triangle C)
{
Scalene constructor super (A,B,C);
}
Other inherited features @Override public void setAngles() {
Scalene_triangle (A, B, C) double s;
Sets angles and if (false==super.isRightAngled()) {
area using AngleA=Math.toDegrees(Math.acos((SideB*SideB+S
setAngles() { these formulae ideC*SideC-SideA*SideA)/(2*SideB*SideC)));
θA = cos-1 (B2+C2-A2)/(2BC)) AngleB=Math.toDegrees(Math.acos((SideA*SideA+S
ideC*SideC-SideB*SideB)/(2*SideA*SideC)));
}
AngleC=Math.toDegrees(Math.acos((SideA*SideA+S
GetArea(){ ideB*SideB-SideC*SideC)/(2*SideA*SideB)));
s= ½(a+b+c) s= 0.5*(SideA+SideB+SideC); Area= Math.sqrt(s*(s-
SideA)*(s-SideB)*(s-SideC)); } }
Area= 𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐) @Override
} public double GetArea()
The if… statement checks if {
triangle is right angle through use of return Area; Override parent method
the method in superclass (its } of getting the Area ( this
}
parent) means “I want to use my
own method”
package triangleobjects_abstract_classes;
Equilateral Triangle code /** * * @author glmoyo */
public class Equilateral_triangle extends
Triangle_Abstract {
Inheriting from Triangle_Abstract public Equilateral_triangle(double A,
using keyword extends double B, double C) {
super (A,B,C); // asking the super class to
construct general triangle
Equilateral
Equilateral triangle }
constructor @Override
Inherited features
public void setAngles() {
AngleA=
Constructor (A,B,C) Sets angles and Math.toDegrees((1/(double)3)*Math.PI);
{ super (A,B,C)} area using AngleB = AngleA; AngleC = AngleA;
setAngle() {Angle A,B,C =60} these formulae }
Area() × 𝑠𝑖𝑑𝑒 @Override
public double GetArea() {
return (Math.sqrt(3)/4) *SideA;
Override parent method }
of getting the Area ( this }
means “I want to use my
own method”
TriangleObjects_Abstract_classes (with main() method)
• This interfaces with the user, asking for user inputs
• Like any programmes or systems we use or design it has three categoric
parts namely: Input, Process and Output
TriangleObjects_Abstract_classes
double s1,s2,s3;
scanUserInput() // input
{
get the three sides inputs S1,S2,S3
}
EvaluateUserInput() // process
{
If Equileteral -- > call the Equilateral Triangle Constructor to create the Equilateral Triangle object
If Isosceles -- > call the Isosceles Triangle Constructor to create the Isosceles Triangle object
If Scalene -- > call the Scalene Triangle Constructor to create the Scalene Triangle object
}
DiplayDesiredOutput() // output
{
Display triangle properties --- > Sides, Angles and Area and description of triangle
}
main() method code
Import java existing system
• This interfaces with the user, asking for user inputs functions into this package
TriangleObjects_Abstract_classes package triangleobjects_abstract_classes;
import java.util.*; //import java.lang.Math; /** * * @author
double s1,s2,s3; Java looks for this name as glmoyo */
Main () a starting point to run public class TriangleObjects_Abstract_classes { /** * @param args
// input -- >scan User Inputs the command line arguments */
{ public static void main(String[] args) { // TODO code application
Primitive data types
get the three sides inputs S1,S2,S3
to carry sides data logic here
}
// process -- > Evaluate User Input double s1,s2,s3;
{ System.out.println ("This programme implements classes to solve
If Equileteral -- > call the Equilateral Triangle Constructor triangles Math\n");
to create the Equilateral Triangle object System.out.println ("please enter first side of a triangle \n");
If Isosceles -- > call the Isosceles Triangle Constructor to Scanner scan = new Scanner (System.in);
create the Isosceles Triangle object s1 =scan.nextDouble(); // get the student name from the console
If Scalene -- > call the Scalene Triangle Constructor to System.out.println ("please enter the second side of a triangle \n");
create the Scalene Triangle object
s2 =scan.nextDouble();
}
// output Diplay Desired Output System.out.println ("please enter the third side of a triangle \n");
{ s3 =scan.nextDouble(); Here we use Scanner object we did not
Display triangle properties --- > Sides, Angles and Area write code for -- > just because we imported
and description of triangle it from java as an existing object
} Similarly we poach the Win System object
main() method code Non-primitive data type (i.e. references to
• This interfaces with the user, asking for user inputs an object with more than one item in it)
Triangle_Abstract Triangle1; // create a reference to a triangle ( a variable that can store an address of an
Triangle object )
TriangleObjects_Abstract_classes if ((s1==s2) && (s2==s3)) {
Feel free to use parent class to create reference to object
Triangle1 =new Equilateral_triangle(s1,s2,s3); // Assign the reference(address) to refer to a particular
double s1,s2,s3; instance of an object Equilateral triangle … but load object with real (concrete) or complete data e.g.
Main () if (Triangle1.ValidTriangle) { Female Mother; // point to Mother (object) as Female (superclass)
Triangle1.TriangleType ="Equilateral "; or
// input -- >scan User Inputs } Woman Mother; // point to Mother(object) as a Woman (subclass)
{ else Assigning object properties
get the three sides inputs S1,S2,S3 { Mother = new Woman() // Yes!! It’s a concrete well defined
Triangle1.TriangleType ="Invalid Triangle"; object that is complete and can exists unambiguously
} }} Mother = new Female() // NO!! because this is too general or
// process -- > Evaluate User Input else if ((s1==s2) || (s2==s3) ) ABSTRACT or ambiguous try (i.e. do you mean Mare(Zebra),
{ { bitch(dog), goose (duck), or mother (human)?
Triangle1 =new Isosceles_triangle(s1,s2,s3); CAN’T CREATE OBJECTS USING ABSTRACT CLASSES
If Equilateral -- > call the Equilateral Triangle Constructor if (Triangle1.ValidTriangle)
to create the Equilateral Triangle object {
If Isosceles -- > call the Isosceles Triangle Constructor to Triangle1.TriangleType ="Isosceles "; Check for validity of Scalene triangle
} else
create the Isosceles Triangle object {
If Scalene -- > call the Scalene Triangle Constructor to Triangle1.TriangleType ="Invalid Triangle";
create the Scalene Triangle object }}
else
Or {
Set Triangle type name to “Invalid Triangle” Triangle1 =new Scalene_triangle(s1,s2,s3);
} if (Triangle1.ValidTriangle)
{ Check for validity of Scalene triangle
// output Diplay Desired Output Triangle1.TriangleType ="Scalene ";
{ }
Display triangle properties --- > Sides, Angles and Area else
{
and description of triangle Triangle1.TriangleType ="Invalid Triangle";
} }}
main() method code
• This interfaces with the user, asking for user inputs
TriangleObjects_Abstract_classes
double s1,s2,s3;
Main ()
// input -- >scan User Inputs
{
get the three sides inputs S1,S2,S3
}
// process -- > Evaluate User Input
{
If Equilateral -- > call the Equilateral Triangle Constructor
to create the Equilateral Triangle object
If Isosceles -- > call the Isosceles Triangle Constructor to Use dot notation to access object properties
create the Isosceles Triangle object
If Scalene -- > call the Scalene Triangle Constructor to
create the Scalene Triangle object
if (Triangle1.ValidTriangle)
Or {
Set Triangle type name to “Invalid Triangle” Triangle1.setAngles();
} System.out.println ("The type of triangle is " + Triangle1.TriangleType + " \n");
Check for validity of Scalene triangle
// output Diplay Desired Output System.out.println ("The angle opposite " + Triangle1.SideA +" is: " + Triangle1.AngleA + " \n");
{ System.out.println ("The angle opposite " + Triangle1.SideB +" is: " + Triangle1.AngleB + " \n");
Display triangle (object instance or one sample) System.out.println ("The angle opposite " + Triangle1.SideC +" is: " + Triangle1.AngleC + " \n");
System.out.println ("The Area of the trangle is: " + Triangle1.GetArea() + " \n"); } } }
properties --- > Sides, Angles and Area and description of
triangle
}
Primitive data types
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character boolean
myBool = true; // Boolean
String myText = "Hello"; // String

Data types are divided into two groups:


•Primitive data types -
includes byte, short, int, long, float, double, boolean and char
•Non-primitive data types - such as String, Arrays and Classes
Primitive data types

Data Type Size Description


byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values

You might also like