Encapsulation and inheritance of classes in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.