Encapsulation Properties: Private Property Type property name
Encapsulation method: Private method return type method name (parameter)
classperson1{PrivateString name; Private intAge ; voidTalk () {System. out. println ("I was:"+name+", this year:"+age+"years"); } Public voidsetName (String str) {name=str; } Public voidSetage (inta) {if(a>0) age=A; Elseage=-A; } PublicString GetName () {returnname; } Public intGetage () {returnAge ; }} Public classClothes { Public Static voidMain (String args[]) {Person1 P=NewPerson1 (); P.setname ("John Doe"); P.setage (- -); P.talk (); }}
I am: John Doe, this year: 25 years old
In Java, you can build on existing classes and then send out new classes.
Class subclass name extends parent class
classperson2{String name; intAge ;} classStudent extends person2{String School;} Public classXXX { Public Static voidMain (String args[]) {Student s=NewStudent (); S.name="John Doe"; S.age= +; S.school="Hkust"; System. out. println ("Name:"+s.name+", Age:"+s.age+", School:"+S.school); } }
Name: John Doe, Age:+, school: hkust
Encapsulation and inheritance of classes in Java